Skip to content

Slightly simplified version of adding KeyToValue for onnx export #4881

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/Microsoft.ML.OnnxConverter/SaveOnnxCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
using Microsoft.ML.Internal.Utilities;
using Microsoft.ML.Model.OnnxConverter;
using Microsoft.ML.Runtime;
using Microsoft.ML.Transforms;
using Newtonsoft.Json;
using static Microsoft.ML.Model.OnnxConverter.OnnxCSharpToProtoWrapper;

Expand Down Expand Up @@ -322,6 +323,26 @@ private void Run(IChannel ch)
nameof(Arguments.LoadPredictor), "We were explicitly told to load the predictor but one was not present.");
}

// If the output schema has KeyDataViewType columns, and it has annotations
// add KeyToValueMappingTransformer to translate the keys back to values
// This is done during Onnx export but not in regular pipelines because onnx does not
// support annotations on tensors
foreach (var column in end.Schema)
{
if ((column.IsHidden) || (!(column.Type.GetItemType() is KeyDataViewType keyType)))
continue;

var metaColumn = column.Annotations.Schema.GetColumnOrNull(AnnotationUtils.Kinds.KeyValues);
if (metaColumn != null
&& metaColumn.Value.Type is VectorDataViewType vectorType
&& keyType.Count == (ulong)vectorType.Size)
{
var outputData = new KeyToValueMappingTransformer(Host, column.Name).Transform(end);
end = outputData;
transforms.AddLast(end as ITransformCanSaveOnnx);
}
}

var model = ConvertTransformListToOnnxModel(ctx, ch, source, end, transforms, _inputsToDrop, _outputsToDrop);

using (var file = Host.CreateOutputFile(_outputModelPath))
Expand Down