machinelearning icon indicating copy to clipboard operation
machinelearning copied to clipboard

Cannot access internal method 'MLContext.CancelExecution()'

Open RockNHawk opened this issue 3 years ago • 9 comments

I have a memory leak issue, and find this similar issue, but CancelExecution in internal.

[BestFriend] internal void CancelExecution() => ((ICancelable) this._env).CancelExecution();

full code

    MLContext context = new MLContext();
    bool useGpu = false;
    OnnxScoringEstimator pipeline = context.Transforms.ApplyOnnxModel(
        modelFile: _modelInfo.ModelPath,
        shapeDictionary: shape.ToDictionary(),
        inputColumnNames: new[] { ColumnNames.Input.InputIds, ColumnNames.Input.AttentionMask, },
        outputColumnNames: new[] { ColumnNames.Output.LastHiddenState, },
        gpuDeviceId: useGpu ? 0 : (int?)null,
        fallbackToCpu: true
    );

    var inputSchemaDef = ToInputSchemaDefinition<InputData>(shape);
    var trainingDataView = context.Data.LoadFromEnumerable(new List<InputData>() { }, inputSchemaDef);
    using var transformer = pipeline.Fit(trainingDataView);

    var outputSchemaDef = ToOutputSchemaDefinition<OutputData>(shape);
    using var predictionEngine = context.Model.CreatePredictionEngine<InputData, OutputData>(transformer, inputSchemaDefinition: inputSchemaDef, outputSchemaDefinition: outputSchemaDef);
    var predictionResult = predictionEngine.Predict(inputData);

@fischja It could be the last trial still running even after automl experiment times out, could you try cancelling context and run again

for (int i = 0; i < 5; i++)
{
    MLContext ml = new MLContext();

    List<MyData> trainingDataList = Enumerable.Range(0, 10000).Select(x => new MyData()).ToList();
    IDataView trainingData = ml.Data.LoadFromEnumerable(trainingDataList);

    var result = ml
        .Auto()
        .CreateRegressionExperiment(maxExperimentTimeInSeconds: 20)
        .Execute(trainData: trainingData, numberOfCVFolds: 3, labelColumnName: "Y");

    ml.CancelExecution();
}

Originally posted by @LittleLittleCloud in https://github.com/dotnet/machinelearning/issues/6188#issuecomment-1121407624

RockNHawk avatar Jul 26 '23 07:07 RockNHawk

I have call this method by reflection, but sill have memory leak, how can I resolve this issue?

RockNHawk avatar Jul 26 '23 07:07 RockNHawk

@RockNHawk The CancelExecution() is exposed in Microsoft.ML.Experimental package. You can install Microsoft.ML.Experimental to get access to that method

For memory leak, would you mind sharing your code with me. I'm happy to take a look

LittleLittleCloud avatar Jul 26 '23 17:07 LittleLittleCloud

@RockNHawk The CancelExecution() is exposed in Microsoft.ML.Experimental package. You can install Microsoft.ML.Experimental to get access to that method

For memory leak, would you mind sharing your code with me. I'm happy to take a look

Of course. Thank you for your help. Here's my code:

The model size is 514MB. After 10 runs, the memory will take up about 7GB. I'm currently adding a GC.Collect() to reduce the memory, and then reduced to 4GB, which is still a lot. And as you know GC.Collect() reduces overall program performance.

TextEmbeddingResult DoGenerateTextEmbedding(StringFragment text)
{
    var tokenizer = _tokenizer.GetTokenizer();
    var inputData = InputData(text, tokenizer);
    var batchSize = 1;
    var maxSize = inputData.InputIds.Length;
    Shape shape = ShapeFactory.CreateShape(0, maxSize);

    MLContext context = new MLContext();

    OnnxScoringEstimator pipeline = context.Transforms.ApplyOnnxModel(
        modelFile: _modelInfo.ModelPath,
        shapeDictionary: shape.ToDictionary(),
        inputColumnNames: new[] { ColumnNames.Input.InputIds, ColumnNames.Input.AttentionMask, },
        outputColumnNames: new[] { ColumnNames.Output.LastHiddenState, },
        gpuDeviceId: null,
        fallbackToCpu: true
    );
    
    var inputSchemaDef = ToInputSchemaDefinition<InputData>(shape);
    var trainingDataView = context.Data.LoadFromEnumerable(new List<InputData>() { }, inputSchemaDef);
    using var transformer = pipeline.Fit(trainingDataView);

    var outputSchemaDef = ToOutputSchemaDefinition<OutputData>(shape);
    using var predictionEngine = context.Model.CreatePredictionEngine<InputData, OutputData>(transformer, inputSchemaDefinition: inputSchemaDef, outputSchemaDefinition: outputSchemaDef);
    var predictionResult = predictionEngine.Predict(inputData);

    var sentenceEmbedding = SentenceEmbeddingUtility.ToSentenceEmbeddings(
        new EmbeddingContext(batchSize, shape.MaxLength, EmbeddingConst.TokenResultDim, predictionResult.LastHiddenState, _dense)
    );

    if (_execteCount > 0 && _execteCount % 10 == 0)
    {
        GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
        GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, false, true);
        if (_execteCount > 999999999)
        {
            _execteCount = 0;
        }
    }
    _execteCount++;

    CancelExecution!.Invoke(context);

    return new(text, sentenceEmbedding);
}

private static readonly Action<MLContext>? CancelExecution = typeof(MLContext).GetMethod("CancelExecution", BindingFlags.Instance | BindingFlags.NonPublic)?.CreateDelegate<Action<MLContext>>();

private static SchemaDefinition ToOutputSchemaDefinition(Shape shape) { var outputSchemaDef = SchemaDefinition.Create(typeof(T)); outputSchemaDef[ColumnNames.Output.LastHiddenState].ColumnType = new VectorDataViewType(NumberDataViewType.Single, shape.OutputDimensions); return outputSchemaDef; }

private static SchemaDefinition ToInputSchemaDefinition<T>(Shape shape)
{
    var inputSchemaDef = SchemaDefinition.Create(typeof(T));
    inputSchemaDef[ColumnNames.Input.InputIds].ColumnType = new VectorDataViewType(NumberDataViewType.Int64, shape.InputDimensions);
    inputSchemaDef[ColumnNames.Input.AttentionMask].ColumnType = new VectorDataViewType(NumberDataViewType.Int64, shape.InputDimensions);
    return inputSchemaDef;
}

private static InputData InputData(StringFragment text, CommonVocabTokenizer tokenizer)
{
    var inputIds = GetInputIds(tokenizer, text.Text);
    // if (inputIds.Length != 512)
    // {
    //     Array.Resize(ref inputIds, 512);
    // }
    var attentionMask = Enumerable.Repeat(1L, inputIds.Length).ToArray();
    var inputData = new InputData(inputIds: inputIds, attentionMask: attentionMask);
    return inputData;
}

RockNHawk avatar Jul 27 '23 02:07 RockNHawk

@LittleLittleCloud Could you spot any problems in this code that could lead to memory leaks? 😀

RockNHawk avatar Aug 11 '23 02:08 RockNHawk

@RockNHawk Sorry I miss the last message, Let me take a look

LittleLittleCloud avatar Aug 11 '23 16:08 LittleLittleCloud

I would assume most of the memory is consumed in DoGenerateTextEmbedding. Looks like DoGenerateTextEmbedding reload the expensive onnx model everytime it gets called, as a workaround maybe you can preload the model and pass its instance to DoGenerateTextEmbedding to avoid reloading?

Another thing I notice is the most recent embedding pipeline won't be GC-ed in your current implementation because the local variable of embedding pipeline is still accessible by the time you call GC. Maybe call GC after you call DoGenerateTextEmbedding would be better?

LittleLittleCloud avatar Aug 11 '23 18:08 LittleLittleCloud

@LittleLittleCloud Thank you for reviewd code and making suggestion ! I will try to modify it. Since the length of the input text is not fixed, I have two modifications.

  1. Change to fixed-length text, and use the same MLContext object for each operation.
  2. Use a MLContext object pool to get the loaded ONNX object model at different lengths (this is expected to consume more memory)

RockNHawk avatar Aug 14 '23 03:08 RockNHawk

Triage: we will need a bit of investigation regarding moving the currently experimental API to GA.

rosebyte avatar Aug 27 '26 09:08 rosebyte

Another use case for moving CancelExecution out of Experimental: stopping a fit that runs past a time budget.

We run our own trainer search over ML.NET trainers (MLoop, which no longer uses Microsoft.ML.AutoML). SdcaLogisticRegression without MaximumNumberOfIterations auto-tunes to 30,000 passes (Auto-tuning parameters: maxIterations = 30000); on a 50-row table with unscaled numeric columns next to one-hot columns, one fit takes ~43 s (Microsoft.ML 5.0.1, NumberOfThreads = 1). Capping the passes is not a substitute, because it changes the model: 10 or 100 passes → AUC 0.50, 1000 → 0.78, the default → 0.81.

The training loops already honor cancellation: calling CancelExecution() from a timer 2 s into that fit throws OperationCanceledException at 2.0 s. Only the entry point is missing from the stable surface — today the choice is reflection on the internal method, or a dependency on Microsoft.ML.Experimental for a single extension method whose API is itself experimental.

Either a public MLContext.CancelExecution() or a CancellationToken accepted by Fit would cover it; a token would also compose with CancellationTokenSource.CancelAfter and the rest of .NET.

birdnamoo avatar Oct 23 '26 03:10 birdnamoo