Skip to content

Conversation

@fedebonisconti
Copy link

Description

Avoids calling TensorInfo#extractShape recursively when curDim + 1 == shape.length.
Thus enhancing the performance by avoiding traversing the entire array to return on the last DFS iteration, as well as unnecessary object autoboxing and method calls.

Motivation and Context

Our Java rest API makes predictions using 100 floats for each tensor, and processing hundreds of tensors for each request, resulting in creating hundreds of thousands of OnnxTensor objects being created per second.

We noticed while profiling the app that about 35% of the cpu sampling was spent in TensorInfo#extractShape method, particularly in the Arrays.get(obj, i) method call, which is called for each element in the array.

Also, the Arrays.get(obj, i) method returns an Object, making floats (or any other native type) get autoboxed to Float objects, and they were subject to garbage collection.

A benchmark using a float[1][100]:

Benchmark Mode Threads Samples Score Score Error (99.9%) Unit
currentImplementation thrpt 1 10 106.992317 0.598410 ops/ms
proposedImplementation thrpt 1 10 11938.071770 143.899310 ops/ms
Benchmark code
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
@Fork(value = 1, jvmArgs = {"-Xms4G", "-Xmx4G", "-Dcom.sun.management.jmxremote", "-Dcom.sun.management.jmxremote.port=9010", "-Dcom.sun.management.jmxremote.authenticate=false",
    "-Dcom.sun.management.jmxremote.ssl=false", "-Djava.rmi.server.hostname=127.0.0.1",
    "-XX:+UseG1GC"})
@Measurement(iterations = 10)
public class ShapeBenchmark {
  float[][] embeddings;


  @Param({"1"})
  int dims;

  @Param({"100"})
  int embeddingsSize;

  @Setup(Level.Trial)
  public void setup() {
    embeddings = new float[dims][embeddingsSize];
    for (int i = 0; i < embeddings.length; i++) {
      for (int j = 0; j < embeddings[i].length; j++) {
        embeddings[i][j] = (float) Math.random();
      }
    }
  }

  @Benchmark
  public long[] currentImplementation() throws OrtException {
    int dimensions = getDimensions(embeddings);
    long[] shape = new long[dimensions];
    extractShape(shape, 0, embeddings);
    return shape;
  }

  @Benchmark
  public long[] proposedImplementation() throws OrtException {
    int dimensions = getDimensions(embeddings);
    long[] shape = new long[dimensions];
    newExtractShape(shape, 0, embeddings);
    return shape;
  }

  // Helper method to get the dimensions of the given array. Copied from TensorInfo#constructFromJavaArray
  public static int getDimensions(Object o) {
    Class<?> objClass = o.getClass();
    int dimensions = 0;
    while (objClass.isArray()) {
      objClass = objClass.getComponentType();
      dimensions++;
    }
    return dimensions;
  }

  @CompilerControl(CompilerControl.Mode.DONT_INLINE)
  // Copied from TensorInfo#extractShape
  public static void extractShape(long[] shape, int curDim, Object obj) throws OrtException {
    if (shape.length != curDim) {
      int curLength = Array.getLength(obj);
      if (curLength == 0) {
        throw new OrtException(
            "Supplied array has a zero dimension at "
                + curDim
                + ", all dimensions must be positive");
      } else if (shape[curDim] == 0L) {
        shape[curDim] = curLength;
      } else if (shape[curDim] != curLength) {
        throw new OrtException(
            "Supplied array is ragged, expected " + shape[curDim] + ", found " + curLength);
      }
      for (int i = 0; i < curLength; i++) {
        extractShape(shape, curDim + 1, Array.get(obj, i));
      }
    }
  }

  @CompilerControl(CompilerControl.Mode.DONT_INLINE)
  public static void newExtractShape(long[] shape, int curDim, Object obj) throws OrtException {
    if (shape.length != curDim) {
      int curLength = Array.getLength(obj);
      if (curLength == 0) {
        throw new OrtException(
            "Supplied array has a zero dimension at "
                + curDim
                + ", all dimensions must be positive");
      } else if (shape[curDim] == 0L) {
        shape[curDim] = curLength;
      } else if (shape[curDim] != curLength) {
        throw new OrtException(
            "Supplied array is ragged, expected " + shape[curDim] + ", found " + curLength);
      }
      int nextDim = curDim + 1;
      if (shape.length != nextDim) {
        for (int i = 0; i < curLength; i++) {
          newExtractShape(shape, nextDim, Array.get(obj, i));
        }
      }
    }
  }

}

Disclaimer: I wasn't able to build onnx locally to run all the test suite for inference in my M3 because im having issues with some dependencies, but added tests for TensorInfo.constructFromJavaArray(obj) and they pass for main branch as well.

@Craigacp
Copy link
Contributor

Craigacp commented May 22, 2025

It's far better to just not supply a multidimensional array when constructing a tensor. Java multidimensional arrays have unfixable performance problems if you want to use them as tensors. Supplying direct (or non-direct) byte buffers should be faster in all cases.

I'll take a look through, but we might want more tests to make sure it catches all the ragged arrays, looks fine once I'd paged the logic back in, it's been a while since I wrote that method.

int nextDim = curDim + 1;
// Avoid traversing the entire array (autoboxing its values) when the next dimension is equal
// to the shape's length
if (shape.length != nextDim) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now you've hoisted the check from line 495 up outside the for loop, you should remove the check at line 495 as it will never fail.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done!

@fedebonisconti
Copy link
Author

I was using FloatBuffer.allocate to supply the array, but for some reason, memory was leaking. Also, using FloatBuffer.allocate creates a HeapBuffer under the hood, which gets copied to a new direct byte buffer. This leads to the creation of DirectByteBuffers, and when direct memory gets full, a major GC is triggered. I still need to try using a DirectBuffer pool managed by our application to avoid major GCs and byte buffer copies, though.

Using the method that takes an object as an argument fixed the leak I was experiencing, but the auto-boxing and iteration add some overhead as well.

@Craigacp
Copy link
Contributor

Craigacp commented May 31, 2025

Yeah, it needs a direct memory allocation somewhere in the JVM or we have to malloc in ORT, copy the data out of the JVM then write to the new memory.

If your inputs are of a known maximum size then preallocate direct buffers and reuse them. It shouldn't leak, though it might look like that till the GC clears the buffers and I'm not sure how quickly the newer collectors like ZGC do that.

@fedebonisconti
Copy link
Author

Inputs might not be always the same size because there are A/B experiments using different models that might have different input sizes.

Im not sure why they were leaking since the JVM has Xmx36g and MaxDirectMemorySize=2g and the app runs out of memory (64gb) anyways after a few days. We're using the v1.18.0.
Using the Java object fixed the leak issue and the memory usage stays at around 44gb, but the app's response time went up and that's how I found this issue while profiling our app.

Although, Im gonna give it a shot using one big buffer and slicing into smaller buffers to supply them to OnnxTensors, instead of using heap buffers!

@fedebonisconti
Copy link
Author

Hi @Craigacp! How are you doing? who else needs to review/approve this PR?

@Craigacp
Copy link
Contributor

Craigacp commented Aug 4, 2025

While I maintain the Java API, I don't work at MS so I can't do the final approval. You need to agree to the CLA before anyone from MS will look at it, and I'd missed that that hadn't happened yet.

@microsoft-github-policy-service
Copy link
Contributor

@fedebonisconti please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”),
and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your
contributions to Microsoft open source projects. This Agreement is effective as of the latest signature
date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants