Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion build/ci/job-template.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,7 +68,7 @@ jobs:
steps:
# Extra MacOS step required to install OS-specific dependencies
- ${{ if and(contains(parameters.pool.vmImage, 'macOS'), not(contains(parameters.name, 'cross'))) }}:
- script: export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=TRUE && brew update && brew unlink libomp && brew install $(Build.SourcesDirectory)/build/libomp.rb --build-from-source --formula
- script: export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=TRUE && brew unlink libomp && brew install $(Build.SourcesDirectory)/build/libomp.rb --build-from-source --formula
displayName: Install MacOS build dependencies
# Extra Apple MacOS step required to install OS-specific dependencies
- ${{ if and(contains(parameters.pool.vmImage, 'macOS'), contains(parameters.name, 'cross')) }}:
Expand Down
13 changes: 13 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/BPE.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -195,6 +195,14 @@ public override IReadOnlyList<Token> Tokenize(string sequence)
return null;
}

/// <summary>
/// Map the tokenized Id to the token.
/// </summary>
/// <param name="id">The Id to map to the token.</param>
/// <param name="skipSpecialTokens">Indicate if want to skip the special tokens during the decoding.</param>
/// <returns>The mapped token of the Id.</returns>
public override string? IdToString(int id, bool skipSpecialTokens = false) => throw new NotImplementedException();

/// <summary>
/// Gets the dictionary mapping tokens to Ids.
/// </summary>
Expand DownExpand Up@@ -443,6 +451,11 @@ internal List<Token> TokenizeWithCache(string sequence)
return tokens;
}

public override bool IsValidChar(char ch)
{
throw new NotImplementedException();
}

internal static readonly List<Token> EmptyTokensList = new();
}
}
27 changes: 27 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/EnglishRoberta.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -135,6 +135,28 @@ public EnglishRoberta(Stream vocabularyStream, Stream mergeStream, Stream highes
public override string? IdToToken(int id, bool skipSpecialTokens = false) =>
skipSpecialTokens && id < 0 ? null : _vocabReverse.TryGetValue(id, out var value) ? value : null;

/// <summary>
/// Map the tokenized Id to the original string.
/// </summary>
/// <param name="id">The Id to map to the string.</param>
/// <param name="skipSpecialTokens">Indicate if want to skip the special tokens during the decoding.</param>
/// <returns>The mapped token of the Id.</returns>
public override string? IdToString(int id, bool skipSpecialTokens = false)
{
if (skipSpecialTokens && id < 0)
return null;
if (_vocabReverse.TryGetValue(id, out var value))
{
var textChars = string.Join("", value)
.Where(c => _unicodeToByte.ContainsKey(c))
.Select(c => _unicodeToByte[c]);
var text = new string(textChars.ToArray());
return text;
}

return null;
}

/// <summary>
/// Save the model data into the vocabulary, merges, and occurrence mapping files.
/// </summary>
Expand DownExpand Up@@ -565,6 +587,11 @@ private List<Token> BpeToken(Span<char> token, Span<int> indexMapping)

return pairs;
}

public override bool IsValidChar(char ch)
{
return _byteToUnicode.ContainsKey(ch);
}
}

/// <summary>
Expand Down
10 changes: 10 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/Model.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,8 @@ public abstract class Model
/// <returns>The mapped token of the Id.</returns>
public abstract string? IdToToken(int id, bool skipSpecialTokens = false);

public abstract string? IdToString(int id, bool skipSpecialTokens = false);

/// <summary>
/// Gets the dictionary mapping tokens to Ids.
/// </summary>
Expand All@@ -57,6 +59,14 @@ public abstract class Model
/// Gets a trainer object to use in training the model.
/// </summary>
public abstract Trainer? GetTrainer();

/// <summary>
/// Return true if the char is valid in the tokenizer; otherwise return false.
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
public abstract bool IsValidChar(char ch);

}

}
10 changes: 9 additions & 1 deletion src/Microsoft.ML.Tokenizers/Tokenizer.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -137,7 +137,10 @@ public TokenizerResult Encode(string sequence)

foreach (int id in ids)
{
tokens.Add(Model.IdToToken(id) ?? "");
if (Model.GetType() == typeof(EnglishRoberta))
tokens.Add(Model.IdToString(id) ?? "");
else
tokens.Add(Model.IdToToken(id) ?? "");
}

return Decoder?.Decode(tokens) ?? string.Join("", tokens);
Expand DownExpand Up@@ -187,5 +190,10 @@ public void TrainFromFiles(
// To Do: support added vocabulary in the tokenizer which will include this returned special_tokens.
// self.add_special_tokens(&special_tokens);
}

public bool IsValidChar(char ch)
{
return Model.IsValidChar(ch);
}
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,19 +17,12 @@
using static TorchSharp.torch.optim.lr_scheduler;
using Microsoft.ML.TorchSharp.Utils;
using Microsoft.ML;
using Microsoft.ML.TorchSharp.NasBert;
using System.IO;
using Microsoft.ML.Data.IO;
using Microsoft.ML.TorchSharp.Loss;
using Microsoft.ML.Transforms.Image;
using static Microsoft.ML.TorchSharp.AutoFormerV2.ObjectDetectionTrainer;
using Microsoft.ML.TorchSharp.AutoFormerV2;
using Microsoft.ML.Tokenizers;
using Microsoft.ML.TorchSharp.Extensions;
using Microsoft.ML.TorchSharp.NasBert.Models;
using static Microsoft.ML.TorchSharp.NasBert.NasBertTrainer;
using TorchSharp.Modules;
using System.Text;
using static Microsoft.ML.Data.AnnotationUtils;

[assembly: LoadableClass(typeof(ObjectDetectionTransformer), null, typeof(SignatureLoadModel),
Expand DownExpand Up@@ -503,7 +496,7 @@ private void CheckInputSchema(SchemaShape inputSchema)
}
}

public class ObjectDetectionTransformer : RowToRowTransformerBase
public class ObjectDetectionTransformer : RowToRowTransformerBase, IDisposable
{
private protected readonly Device Device;
private protected readonly AutoFormerV2 Model;
Expand All@@ -522,6 +515,7 @@ public class ObjectDetectionTransformer : RowToRowTransformerBase

private static readonly FuncStaticMethodInfo1<object, Delegate> _decodeInitMethodInfo
= new FuncStaticMethodInfo1<object, Delegate>(DecodeInit<int>);
private bool _disposedValue;

internal ObjectDetectionTransformer(IHostEnvironment env, ObjectDetectionTrainer.Options options, AutoFormerV2 model, DataViewSchema.DetachedColumn labelColumn)
: base(Contracts.CheckRef(env, nameof(env)).Register(nameof(ObjectDetectionTransformer)))
Expand DownExpand Up@@ -992,5 +986,31 @@ private protected override Func<int, bool> GetDependenciesCore(Func<int, bool> a
return col => (activeOutput(0) || activeOutput(1) || activeOutput(2)) && _inputColIndices.Any(i => i == col);
}
}

protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
}

Model.Dispose();
_disposedValue = true;
}
}

~ObjectDetectionTransformer()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: false);
}

public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
16 changes: 16 additions & 0 deletions src/Microsoft.ML.TorchSharp/NasBert/BertModelType.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Text;

namespace Microsoft.ML.TorchSharp.NasBert
{
internal enum BertModelType
{
NasBert,
Roberta
}
}
4 changes: 3 additions & 1 deletion src/Microsoft.ML.TorchSharp/NasBert/BertTaskType.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,8 @@ public enum BertTaskType
None = 0,
MaskedLM = 1,
TextClassification = 2,
SentenceRegression = 3
SentenceRegression = 3,
NameEntityRecognition = 4,
QuestionAnswering = 5
}
}
3 changes: 0 additions & 3 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/BaseHead.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,9 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Text;
using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
Expand Down
11 changes: 5 additions & 6 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/BaseModel.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,23 +3,22 @@
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ML.TorchSharp.Utils;
using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
{
internal abstract class BaseModel : torch.nn.Module<torch.Tensor, torch.Tensor, torch.Tensor>
{
protected readonly NasBertTrainer.NasBertOptions Options;
public BertTaskType HeadType => Options.TaskType;
public BertModelType EncoderType => Options.ModelType;

//public ModelType EncoderType => Options.ModelType;
public BertTaskType HeadType => Options.TaskType;

#pragma warning disable CA1024 // Use properties where appropriate: Modules should be fields in TorchSharp
public abstract TransformerEncoder GetEncoder();

public abstract BaseHead GetHead();

#pragma warning restore CA1024 // Use properties where appropriate

protected BaseModel(NasBertTrainer.NasBertOptions options)
Expand Down
36 changes: 36 additions & 0 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/ModelPrediction.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
{
internal sealed class ModelForPrediction : NasBertModel

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

NERInferenceModel?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

This isn't for NER. Its for SentenceSimilarity and TextClassification. How about TextModel? TextModelForPrediction? Thoughts?

{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_PrivateFieldName:Private field name not in: _camelCase format", Justification = "Has to match TorchSharp model.")]
private readonly PredictionHead PredictionHead;
Comment thread
JakeRadMSFT marked this conversation as resolved.

public override BaseHead GetHead() => PredictionHead;

public ModelForPrediction(NasBertTrainer.NasBertOptions options, int padIndex, int symbolsCount, int numClasses)
: base(options, padIndex, symbolsCount)
{
PredictionHead = new PredictionHead(
inputDim: Options.EncoderOutputDim,
numClasses: numClasses,
dropoutRate: Options.PoolerDropout);
Initialize();
RegisterComponents();
}

[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_GeneralName:This name should be PascalCased", Justification = "Need to match TorchSharp.")]
public override torch.Tensor forward(torch.Tensor srcTokens, torch.Tensor tokenMask = null)
{
using var disposeScope = torch.NewDisposeScope();
var x = ExtractFeatures(srcTokens);
x = PredictionHead.call(x);
return x.MoveToOuterDisposeScope();
}
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion build/ci/job-template.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,7 +68,7 @@ jobs:
steps:
# Extra MacOS step required to install OS-specific dependencies
- ${{ if and(contains(parameters.pool.vmImage, 'macOS'), not(contains(parameters.name, 'cross'))) }}:
- script: export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=TRUE && brew update && brew unlink libomp && brew install $(Build.SourcesDirectory)/build/libomp.rb --build-from-source --formula
- script: export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=TRUE && brew unlink libomp && brew install $(Build.SourcesDirectory)/build/libomp.rb --build-from-source --formula
displayName: Install MacOS build dependencies
# Extra Apple MacOS step required to install OS-specific dependencies
- ${{ if and(contains(parameters.pool.vmImage, 'macOS'), contains(parameters.name, 'cross')) }}:
Expand Down
13 changes: 13 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/BPE.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -195,6 +195,14 @@ public override IReadOnlyList<Token> Tokenize(string sequence)
return null;
}

/// <summary>
/// Map the tokenized Id to the token.
/// </summary>
/// <param name="id">The Id to map to the token.</param>
/// <param name="skipSpecialTokens">Indicate if want to skip the special tokens during the decoding.</param>
/// <returns>The mapped token of the Id.</returns>
public override string? IdToString(int id, bool skipSpecialTokens = false) => throw new NotImplementedException();

/// <summary>
/// Gets the dictionary mapping tokens to Ids.
/// </summary>
Expand DownExpand Up@@ -443,6 +451,11 @@ internal List<Token> TokenizeWithCache(string sequence)
return tokens;
}

public override bool IsValidChar(char ch)
{
throw new NotImplementedException();
}

internal static readonly List<Token> EmptyTokensList = new();
}
}
27 changes: 27 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/EnglishRoberta.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -135,6 +135,28 @@ public EnglishRoberta(Stream vocabularyStream, Stream mergeStream, Stream highes
public override string? IdToToken(int id, bool skipSpecialTokens = false) =>
skipSpecialTokens && id < 0 ? null : _vocabReverse.TryGetValue(id, out var value) ? value : null;

/// <summary>
/// Map the tokenized Id to the original string.
/// </summary>
/// <param name="id">The Id to map to the string.</param>
/// <param name="skipSpecialTokens">Indicate if want to skip the special tokens during the decoding.</param>
/// <returns>The mapped token of the Id.</returns>
public override string? IdToString(int id, bool skipSpecialTokens = false)
{
if (skipSpecialTokens && id < 0)
return null;
if (_vocabReverse.TryGetValue(id, out var value))
{
var textChars = string.Join("", value)
.Where(c => _unicodeToByte.ContainsKey(c))
.Select(c => _unicodeToByte[c]);
var text = new string(textChars.ToArray());
return text;
}

return null;
}

/// <summary>
/// Save the model data into the vocabulary, merges, and occurrence mapping files.
/// </summary>
Expand DownExpand Up@@ -565,6 +587,11 @@ private List<Token> BpeToken(Span<char> token, Span<int> indexMapping)

return pairs;
}

public override bool IsValidChar(char ch)
{
return _byteToUnicode.ContainsKey(ch);
}
}

/// <summary>
Expand Down
10 changes: 10 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/Model.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,8 @@ public abstract class Model
/// <returns>The mapped token of the Id.</returns>
public abstract string? IdToToken(int id, bool skipSpecialTokens = false);

public abstract string? IdToString(int id, bool skipSpecialTokens = false);

/// <summary>
/// Gets the dictionary mapping tokens to Ids.
/// </summary>
Expand All@@ -57,6 +59,14 @@ public abstract class Model
/// Gets a trainer object to use in training the model.
/// </summary>
public abstract Trainer? GetTrainer();

/// <summary>
/// Return true if the char is valid in the tokenizer; otherwise return false.
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
public abstract bool IsValidChar(char ch);

}

}
10 changes: 9 additions & 1 deletion src/Microsoft.ML.Tokenizers/Tokenizer.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -137,7 +137,10 @@ public TokenizerResult Encode(string sequence)

foreach (int id in ids)
{
tokens.Add(Model.IdToToken(id) ?? "");
if (Model.GetType() == typeof(EnglishRoberta))
tokens.Add(Model.IdToString(id) ?? "");
else
tokens.Add(Model.IdToToken(id) ?? "");
}

return Decoder?.Decode(tokens) ?? string.Join("", tokens);
Expand DownExpand Up@@ -187,5 +190,10 @@ public void TrainFromFiles(
// To Do: support added vocabulary in the tokenizer which will include this returned special_tokens.
// self.add_special_tokens(&special_tokens);
}

public bool IsValidChar(char ch)
{
return Model.IsValidChar(ch);
}
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,19 +17,12 @@
using static TorchSharp.torch.optim.lr_scheduler;
using Microsoft.ML.TorchSharp.Utils;
using Microsoft.ML;
using Microsoft.ML.TorchSharp.NasBert;
using System.IO;
using Microsoft.ML.Data.IO;
using Microsoft.ML.TorchSharp.Loss;
using Microsoft.ML.Transforms.Image;
using static Microsoft.ML.TorchSharp.AutoFormerV2.ObjectDetectionTrainer;
using Microsoft.ML.TorchSharp.AutoFormerV2;
using Microsoft.ML.Tokenizers;
using Microsoft.ML.TorchSharp.Extensions;
using Microsoft.ML.TorchSharp.NasBert.Models;
using static Microsoft.ML.TorchSharp.NasBert.NasBertTrainer;
using TorchSharp.Modules;
using System.Text;
using static Microsoft.ML.Data.AnnotationUtils;

[assembly: LoadableClass(typeof(ObjectDetectionTransformer), null, typeof(SignatureLoadModel),
Expand DownExpand Up@@ -503,7 +496,7 @@ private void CheckInputSchema(SchemaShape inputSchema)
}
}

public class ObjectDetectionTransformer : RowToRowTransformerBase
public class ObjectDetectionTransformer : RowToRowTransformerBase, IDisposable
{
private protected readonly Device Device;
private protected readonly AutoFormerV2 Model;
Expand All@@ -522,6 +515,7 @@ public class ObjectDetectionTransformer : RowToRowTransformerBase

private static readonly FuncStaticMethodInfo1<object, Delegate> _decodeInitMethodInfo
= new FuncStaticMethodInfo1<object, Delegate>(DecodeInit<int>);
private bool _disposedValue;

internal ObjectDetectionTransformer(IHostEnvironment env, ObjectDetectionTrainer.Options options, AutoFormerV2 model, DataViewSchema.DetachedColumn labelColumn)
: base(Contracts.CheckRef(env, nameof(env)).Register(nameof(ObjectDetectionTransformer)))
Expand DownExpand Up@@ -992,5 +986,31 @@ private protected override Func<int, bool> GetDependenciesCore(Func<int, bool> a
return col => (activeOutput(0) || activeOutput(1) || activeOutput(2)) && _inputColIndices.Any(i => i == col);
}
}

protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
}

Model.Dispose();
_disposedValue = true;
}
}

~ObjectDetectionTransformer()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: false);
}

public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
16 changes: 16 additions & 0 deletions src/Microsoft.ML.TorchSharp/NasBert/BertModelType.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Text;

namespace Microsoft.ML.TorchSharp.NasBert
{
internal enum BertModelType
{
NasBert,
Roberta
}
}
4 changes: 3 additions & 1 deletion src/Microsoft.ML.TorchSharp/NasBert/BertTaskType.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,8 @@ public enum BertTaskType
None = 0,
MaskedLM = 1,
TextClassification = 2,
SentenceRegression = 3
SentenceRegression = 3,
NameEntityRecognition = 4,
QuestionAnswering = 5
}
}
3 changes: 0 additions & 3 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/BaseHead.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,9 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Text;
using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
Expand Down
11 changes: 5 additions & 6 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/BaseModel.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,23 +3,22 @@
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ML.TorchSharp.Utils;
using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
{
internal abstract class BaseModel : torch.nn.Module<torch.Tensor, torch.Tensor, torch.Tensor>
{
protected readonly NasBertTrainer.NasBertOptions Options;
public BertTaskType HeadType => Options.TaskType;
public BertModelType EncoderType => Options.ModelType;

//public ModelType EncoderType => Options.ModelType;
public BertTaskType HeadType => Options.TaskType;

#pragma warning disable CA1024 // Use properties where appropriate: Modules should be fields in TorchSharp
public abstract TransformerEncoder GetEncoder();

public abstract BaseHead GetHead();

#pragma warning restore CA1024 // Use properties where appropriate

protected BaseModel(NasBertTrainer.NasBertOptions options)
Expand Down
36 changes: 36 additions & 0 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/ModelPrediction.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
{
internal sealed class ModelForPrediction : NasBertModel

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

NERInferenceModel?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

This isn't for NER. Its for SentenceSimilarity and TextClassification. How about TextModel? TextModelForPrediction? Thoughts?

{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_PrivateFieldName:Private field name not in: _camelCase format", Justification = "Has to match TorchSharp model.")]
private readonly PredictionHead PredictionHead;
Comment thread
JakeRadMSFT marked this conversation as resolved.

public override BaseHead GetHead() => PredictionHead;

public ModelForPrediction(NasBertTrainer.NasBertOptions options, int padIndex, int symbolsCount, int numClasses)
: base(options, padIndex, symbolsCount)
{
PredictionHead = new PredictionHead(
inputDim: Options.EncoderOutputDim,
numClasses: numClasses,
dropoutRate: Options.PoolerDropout);
Initialize();
RegisterComponents();
}

[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_GeneralName:This name should be PascalCased", Justification = "Need to match TorchSharp.")]
public override torch.Tensor forward(torch.Tensor srcTokens, torch.Tensor tokenMask = null)
{
using var disposeScope = torch.NewDisposeScope();
var x = ExtractFeatures(srcTokens);
x = PredictionHead.call(x);
return x.MoveToOuterDisposeScope();
}
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion build/ci/job-template.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,7 +68,7 @@ jobs:
steps:
# Extra MacOS step required to install OS-specific dependencies
- ${{ if and(contains(parameters.pool.vmImage, 'macOS'), not(contains(parameters.name, 'cross'))) }}:
- script: export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=TRUE && brew update && brew unlink libomp && brew install $(Build.SourcesDirectory)/build/libomp.rb --build-from-source --formula
- script: export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=TRUE && brew unlink libomp && brew install $(Build.SourcesDirectory)/build/libomp.rb --build-from-source --formula
displayName: Install MacOS build dependencies
# Extra Apple MacOS step required to install OS-specific dependencies
- ${{ if and(contains(parameters.pool.vmImage, 'macOS'), contains(parameters.name, 'cross')) }}:
Expand Down
13 changes: 13 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/BPE.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -195,6 +195,14 @@ public override IReadOnlyList<Token> Tokenize(string sequence)
return null;
}

/// <summary>
/// Map the tokenized Id to the token.
/// </summary>
/// <param name="id">The Id to map to the token.</param>
/// <param name="skipSpecialTokens">Indicate if want to skip the special tokens during the decoding.</param>
/// <returns>The mapped token of the Id.</returns>
public override string? IdToString(int id, bool skipSpecialTokens = false) => throw new NotImplementedException();

/// <summary>
/// Gets the dictionary mapping tokens to Ids.
/// </summary>
Expand DownExpand Up@@ -443,6 +451,11 @@ internal List<Token> TokenizeWithCache(string sequence)
return tokens;
}

public override bool IsValidChar(char ch)
{
throw new NotImplementedException();
}

internal static readonly List<Token> EmptyTokensList = new();
}
}
27 changes: 27 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/EnglishRoberta.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -135,6 +135,28 @@ public EnglishRoberta(Stream vocabularyStream, Stream mergeStream, Stream highes
public override string? IdToToken(int id, bool skipSpecialTokens = false) =>
skipSpecialTokens && id < 0 ? null : _vocabReverse.TryGetValue(id, out var value) ? value : null;

/// <summary>
/// Map the tokenized Id to the original string.
/// </summary>
/// <param name="id">The Id to map to the string.</param>
/// <param name="skipSpecialTokens">Indicate if want to skip the special tokens during the decoding.</param>
/// <returns>The mapped token of the Id.</returns>
public override string? IdToString(int id, bool skipSpecialTokens = false)
{
if (skipSpecialTokens && id < 0)
return null;
if (_vocabReverse.TryGetValue(id, out var value))
{
var textChars = string.Join("", value)
.Where(c => _unicodeToByte.ContainsKey(c))
.Select(c => _unicodeToByte[c]);
var text = new string(textChars.ToArray());
return text;
}

return null;
}

/// <summary>
/// Save the model data into the vocabulary, merges, and occurrence mapping files.
/// </summary>
Expand DownExpand Up@@ -565,6 +587,11 @@ private List<Token> BpeToken(Span<char> token, Span<int> indexMapping)

return pairs;
}

public override bool IsValidChar(char ch)
{
return _byteToUnicode.ContainsKey(ch);
}
}

/// <summary>
Expand Down
10 changes: 10 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/Model.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,8 @@ public abstract class Model
/// <returns>The mapped token of the Id.</returns>
public abstract string? IdToToken(int id, bool skipSpecialTokens = false);

public abstract string? IdToString(int id, bool skipSpecialTokens = false);

/// <summary>
/// Gets the dictionary mapping tokens to Ids.
/// </summary>
Expand All@@ -57,6 +59,14 @@ public abstract class Model
/// Gets a trainer object to use in training the model.
/// </summary>
public abstract Trainer? GetTrainer();

/// <summary>
/// Return true if the char is valid in the tokenizer; otherwise return false.
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
public abstract bool IsValidChar(char ch);

}

}
10 changes: 9 additions & 1 deletion src/Microsoft.ML.Tokenizers/Tokenizer.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -137,7 +137,10 @@ public TokenizerResult Encode(string sequence)

foreach (int id in ids)
{
tokens.Add(Model.IdToToken(id) ?? "");
if (Model.GetType() == typeof(EnglishRoberta))
tokens.Add(Model.IdToString(id) ?? "");
else
tokens.Add(Model.IdToToken(id) ?? "");
}

return Decoder?.Decode(tokens) ?? string.Join("", tokens);
Expand DownExpand Up@@ -187,5 +190,10 @@ public void TrainFromFiles(
// To Do: support added vocabulary in the tokenizer which will include this returned special_tokens.
// self.add_special_tokens(&special_tokens);
}

public bool IsValidChar(char ch)
{
return Model.IsValidChar(ch);
}
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,19 +17,12 @@
using static TorchSharp.torch.optim.lr_scheduler;
using Microsoft.ML.TorchSharp.Utils;
using Microsoft.ML;
using Microsoft.ML.TorchSharp.NasBert;
using System.IO;
using Microsoft.ML.Data.IO;
using Microsoft.ML.TorchSharp.Loss;
using Microsoft.ML.Transforms.Image;
using static Microsoft.ML.TorchSharp.AutoFormerV2.ObjectDetectionTrainer;
using Microsoft.ML.TorchSharp.AutoFormerV2;
using Microsoft.ML.Tokenizers;
using Microsoft.ML.TorchSharp.Extensions;
using Microsoft.ML.TorchSharp.NasBert.Models;
using static Microsoft.ML.TorchSharp.NasBert.NasBertTrainer;
using TorchSharp.Modules;
using System.Text;
using static Microsoft.ML.Data.AnnotationUtils;

[assembly: LoadableClass(typeof(ObjectDetectionTransformer), null, typeof(SignatureLoadModel),
Expand DownExpand Up@@ -503,7 +496,7 @@ private void CheckInputSchema(SchemaShape inputSchema)
}
}

public class ObjectDetectionTransformer : RowToRowTransformerBase
public class ObjectDetectionTransformer : RowToRowTransformerBase, IDisposable
{
private protected readonly Device Device;
private protected readonly AutoFormerV2 Model;
Expand All@@ -522,6 +515,7 @@ public class ObjectDetectionTransformer : RowToRowTransformerBase

private static readonly FuncStaticMethodInfo1<object, Delegate> _decodeInitMethodInfo
= new FuncStaticMethodInfo1<object, Delegate>(DecodeInit<int>);
private bool _disposedValue;

internal ObjectDetectionTransformer(IHostEnvironment env, ObjectDetectionTrainer.Options options, AutoFormerV2 model, DataViewSchema.DetachedColumn labelColumn)
: base(Contracts.CheckRef(env, nameof(env)).Register(nameof(ObjectDetectionTransformer)))
Expand DownExpand Up@@ -992,5 +986,31 @@ private protected override Func<int, bool> GetDependenciesCore(Func<int, bool> a
return col => (activeOutput(0) || activeOutput(1) || activeOutput(2)) && _inputColIndices.Any(i => i == col);
}
}

protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
}

Model.Dispose();
_disposedValue = true;
}
}

~ObjectDetectionTransformer()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: false);
}

public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
16 changes: 16 additions & 0 deletions src/Microsoft.ML.TorchSharp/NasBert/BertModelType.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Text;

namespace Microsoft.ML.TorchSharp.NasBert
{
internal enum BertModelType
{
NasBert,
Roberta
}
}
4 changes: 3 additions & 1 deletion src/Microsoft.ML.TorchSharp/NasBert/BertTaskType.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,8 @@ public enum BertTaskType
None = 0,
MaskedLM = 1,
TextClassification = 2,
SentenceRegression = 3
SentenceRegression = 3,
NameEntityRecognition = 4,
QuestionAnswering = 5
}
}
3 changes: 0 additions & 3 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/BaseHead.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,9 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Text;
using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
Expand Down
11 changes: 5 additions & 6 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/BaseModel.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,23 +3,22 @@
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ML.TorchSharp.Utils;
using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
{
internal abstract class BaseModel : torch.nn.Module<torch.Tensor, torch.Tensor, torch.Tensor>
{
protected readonly NasBertTrainer.NasBertOptions Options;
public BertTaskType HeadType => Options.TaskType;
public BertModelType EncoderType => Options.ModelType;

//public ModelType EncoderType => Options.ModelType;
public BertTaskType HeadType => Options.TaskType;

#pragma warning disable CA1024 // Use properties where appropriate: Modules should be fields in TorchSharp
public abstract TransformerEncoder GetEncoder();

public abstract BaseHead GetHead();

#pragma warning restore CA1024 // Use properties where appropriate

protected BaseModel(NasBertTrainer.NasBertOptions options)
Expand Down
36 changes: 36 additions & 0 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/ModelPrediction.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
{
internal sealed class ModelForPrediction : NasBertModel

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

NERInferenceModel?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

This isn't for NER. Its for SentenceSimilarity and TextClassification. How about TextModel? TextModelForPrediction? Thoughts?

{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_PrivateFieldName:Private field name not in: _camelCase format", Justification = "Has to match TorchSharp model.")]
private readonly PredictionHead PredictionHead;
Comment thread
JakeRadMSFT marked this conversation as resolved.

public override BaseHead GetHead() => PredictionHead;

public ModelForPrediction(NasBertTrainer.NasBertOptions options, int padIndex, int symbolsCount, int numClasses)
: base(options, padIndex, symbolsCount)
{
PredictionHead = new PredictionHead(
inputDim: Options.EncoderOutputDim,
numClasses: numClasses,
dropoutRate: Options.PoolerDropout);
Initialize();
RegisterComponents();
}

[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_GeneralName:This name should be PascalCased", Justification = "Need to match TorchSharp.")]
public override torch.Tensor forward(torch.Tensor srcTokens, torch.Tensor tokenMask = null)
{
using var disposeScope = torch.NewDisposeScope();
var x = ExtractFeatures(srcTokens);
x = PredictionHead.call(x);
return x.MoveToOuterDisposeScope();
}
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion build/ci/job-template.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,7 +68,7 @@ jobs:
steps:
# Extra MacOS step required to install OS-specific dependencies
- ${{ if and(contains(parameters.pool.vmImage, 'macOS'), not(contains(parameters.name, 'cross'))) }}:
- script: export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=TRUE && brew update && brew unlink libomp && brew install $(Build.SourcesDirectory)/build/libomp.rb --build-from-source --formula
- script: export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=TRUE && brew unlink libomp && brew install $(Build.SourcesDirectory)/build/libomp.rb --build-from-source --formula
displayName: Install MacOS build dependencies
# Extra Apple MacOS step required to install OS-specific dependencies
- ${{ if and(contains(parameters.pool.vmImage, 'macOS'), contains(parameters.name, 'cross')) }}:
Expand Down
13 changes: 13 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/BPE.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -195,6 +195,14 @@ public override IReadOnlyList<Token> Tokenize(string sequence)
return null;
}

/// <summary>
/// Map the tokenized Id to the token.
/// </summary>
/// <param name="id">The Id to map to the token.</param>
/// <param name="skipSpecialTokens">Indicate if want to skip the special tokens during the decoding.</param>
/// <returns>The mapped token of the Id.</returns>
public override string? IdToString(int id, bool skipSpecialTokens = false) => throw new NotImplementedException();

/// <summary>
/// Gets the dictionary mapping tokens to Ids.
/// </summary>
Expand DownExpand Up@@ -443,6 +451,11 @@ internal List<Token> TokenizeWithCache(string sequence)
return tokens;
}

public override bool IsValidChar(char ch)
{
throw new NotImplementedException();
}

internal static readonly List<Token> EmptyTokensList = new();
}
}
27 changes: 27 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/EnglishRoberta.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -135,6 +135,28 @@ public EnglishRoberta(Stream vocabularyStream, Stream mergeStream, Stream highes
public override string? IdToToken(int id, bool skipSpecialTokens = false) =>
skipSpecialTokens && id < 0 ? null : _vocabReverse.TryGetValue(id, out var value) ? value : null;

/// <summary>
/// Map the tokenized Id to the original string.
/// </summary>
/// <param name="id">The Id to map to the string.</param>
/// <param name="skipSpecialTokens">Indicate if want to skip the special tokens during the decoding.</param>
/// <returns>The mapped token of the Id.</returns>
public override string? IdToString(int id, bool skipSpecialTokens = false)
{
if (skipSpecialTokens && id < 0)
return null;
if (_vocabReverse.TryGetValue(id, out var value))
{
var textChars = string.Join("", value)
.Where(c => _unicodeToByte.ContainsKey(c))
.Select(c => _unicodeToByte[c]);
var text = new string(textChars.ToArray());
return text;
}

return null;
}

/// <summary>
/// Save the model data into the vocabulary, merges, and occurrence mapping files.
/// </summary>
Expand DownExpand Up@@ -565,6 +587,11 @@ private List<Token> BpeToken(Span<char> token, Span<int> indexMapping)

return pairs;
}

public override bool IsValidChar(char ch)
{
return _byteToUnicode.ContainsKey(ch);
}
}

/// <summary>
Expand Down
10 changes: 10 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/Model.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,8 @@ public abstract class Model
/// <returns>The mapped token of the Id.</returns>
public abstract string? IdToToken(int id, bool skipSpecialTokens = false);

public abstract string? IdToString(int id, bool skipSpecialTokens = false);

/// <summary>
/// Gets the dictionary mapping tokens to Ids.
/// </summary>
Expand All@@ -57,6 +59,14 @@ public abstract class Model
/// Gets a trainer object to use in training the model.
/// </summary>
public abstract Trainer? GetTrainer();

/// <summary>
/// Return true if the char is valid in the tokenizer; otherwise return false.
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
public abstract bool IsValidChar(char ch);

}

}
10 changes: 9 additions & 1 deletion src/Microsoft.ML.Tokenizers/Tokenizer.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -137,7 +137,10 @@ public TokenizerResult Encode(string sequence)

foreach (int id in ids)
{
tokens.Add(Model.IdToToken(id) ?? "");
if (Model.GetType() == typeof(EnglishRoberta))
tokens.Add(Model.IdToString(id) ?? "");
else
tokens.Add(Model.IdToToken(id) ?? "");
}

return Decoder?.Decode(tokens) ?? string.Join("", tokens);
Expand DownExpand Up@@ -187,5 +190,10 @@ public void TrainFromFiles(
// To Do: support added vocabulary in the tokenizer which will include this returned special_tokens.
// self.add_special_tokens(&special_tokens);
}

public bool IsValidChar(char ch)
{
return Model.IsValidChar(ch);
}
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,19 +17,12 @@
using static TorchSharp.torch.optim.lr_scheduler;
using Microsoft.ML.TorchSharp.Utils;
using Microsoft.ML;
using Microsoft.ML.TorchSharp.NasBert;
using System.IO;
using Microsoft.ML.Data.IO;
using Microsoft.ML.TorchSharp.Loss;
using Microsoft.ML.Transforms.Image;
using static Microsoft.ML.TorchSharp.AutoFormerV2.ObjectDetectionTrainer;
using Microsoft.ML.TorchSharp.AutoFormerV2;
using Microsoft.ML.Tokenizers;
using Microsoft.ML.TorchSharp.Extensions;
using Microsoft.ML.TorchSharp.NasBert.Models;
using static Microsoft.ML.TorchSharp.NasBert.NasBertTrainer;
using TorchSharp.Modules;
using System.Text;
using static Microsoft.ML.Data.AnnotationUtils;

[assembly: LoadableClass(typeof(ObjectDetectionTransformer), null, typeof(SignatureLoadModel),
Expand DownExpand Up@@ -503,7 +496,7 @@ private void CheckInputSchema(SchemaShape inputSchema)
}
}

public class ObjectDetectionTransformer : RowToRowTransformerBase
public class ObjectDetectionTransformer : RowToRowTransformerBase, IDisposable
{
private protected readonly Device Device;
private protected readonly AutoFormerV2 Model;
Expand All@@ -522,6 +515,7 @@ public class ObjectDetectionTransformer : RowToRowTransformerBase

private static readonly FuncStaticMethodInfo1<object, Delegate> _decodeInitMethodInfo
= new FuncStaticMethodInfo1<object, Delegate>(DecodeInit<int>);
private bool _disposedValue;

internal ObjectDetectionTransformer(IHostEnvironment env, ObjectDetectionTrainer.Options options, AutoFormerV2 model, DataViewSchema.DetachedColumn labelColumn)
: base(Contracts.CheckRef(env, nameof(env)).Register(nameof(ObjectDetectionTransformer)))
Expand DownExpand Up@@ -992,5 +986,31 @@ private protected override Func<int, bool> GetDependenciesCore(Func<int, bool> a
return col => (activeOutput(0) || activeOutput(1) || activeOutput(2)) && _inputColIndices.Any(i => i == col);
}
}

protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
}

Model.Dispose();
_disposedValue = true;
}
}

~ObjectDetectionTransformer()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: false);
}

public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
16 changes: 16 additions & 0 deletions src/Microsoft.ML.TorchSharp/NasBert/BertModelType.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Text;

namespace Microsoft.ML.TorchSharp.NasBert
{
internal enum BertModelType
{
NasBert,
Roberta
}
}
4 changes: 3 additions & 1 deletion src/Microsoft.ML.TorchSharp/NasBert/BertTaskType.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,8 @@ public enum BertTaskType
None = 0,
MaskedLM = 1,
TextClassification = 2,
SentenceRegression = 3
SentenceRegression = 3,
NameEntityRecognition = 4,
QuestionAnswering = 5
}
}
3 changes: 0 additions & 3 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/BaseHead.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,9 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Text;
using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
Expand Down
11 changes: 5 additions & 6 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/BaseModel.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,23 +3,22 @@
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ML.TorchSharp.Utils;
using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
{
internal abstract class BaseModel : torch.nn.Module<torch.Tensor, torch.Tensor, torch.Tensor>
{
protected readonly NasBertTrainer.NasBertOptions Options;
public BertTaskType HeadType => Options.TaskType;
public BertModelType EncoderType => Options.ModelType;

//public ModelType EncoderType => Options.ModelType;
public BertTaskType HeadType => Options.TaskType;

#pragma warning disable CA1024 // Use properties where appropriate: Modules should be fields in TorchSharp
public abstract TransformerEncoder GetEncoder();

public abstract BaseHead GetHead();

#pragma warning restore CA1024 // Use properties where appropriate

protected BaseModel(NasBertTrainer.NasBertOptions options)
Expand Down
36 changes: 36 additions & 0 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/ModelPrediction.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
{
internal sealed class ModelForPrediction : NasBertModel

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

NERInferenceModel?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

This isn't for NER. Its for SentenceSimilarity and TextClassification. How about TextModel? TextModelForPrediction? Thoughts?

{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_PrivateFieldName:Private field name not in: _camelCase format", Justification = "Has to match TorchSharp model.")]
private readonly PredictionHead PredictionHead;
Comment thread
JakeRadMSFT marked this conversation as resolved.

public override BaseHead GetHead() => PredictionHead;

public ModelForPrediction(NasBertTrainer.NasBertOptions options, int padIndex, int symbolsCount, int numClasses)
: base(options, padIndex, symbolsCount)
{
PredictionHead = new PredictionHead(
inputDim: Options.EncoderOutputDim,
numClasses: numClasses,
dropoutRate: Options.PoolerDropout);
Initialize();
RegisterComponents();
}

[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_GeneralName:This name should be PascalCased", Justification = "Need to match TorchSharp.")]
public override torch.Tensor forward(torch.Tensor srcTokens, torch.Tensor tokenMask = null)
{
using var disposeScope = torch.NewDisposeScope();
var x = ExtractFeatures(srcTokens);
x = PredictionHead.call(x);
return x.MoveToOuterDisposeScope();
}
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion build/ci/job-template.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,7 +68,7 @@ jobs:
steps:
# Extra MacOS step required to install OS-specific dependencies
- ${{ if and(contains(parameters.pool.vmImage, 'macOS'), not(contains(parameters.name, 'cross'))) }}:
- script: export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=TRUE && brew update && brew unlink libomp && brew install $(Build.SourcesDirectory)/build/libomp.rb --build-from-source --formula
- script: export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=TRUE && brew unlink libomp && brew install $(Build.SourcesDirectory)/build/libomp.rb --build-from-source --formula
displayName: Install MacOS build dependencies
# Extra Apple MacOS step required to install OS-specific dependencies
- ${{ if and(contains(parameters.pool.vmImage, 'macOS'), contains(parameters.name, 'cross')) }}:
Expand Down
13 changes: 13 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/BPE.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -195,6 +195,14 @@ public override IReadOnlyList<Token> Tokenize(string sequence)
return null;
}

/// <summary>
/// Map the tokenized Id to the token.
/// </summary>
/// <param name="id">The Id to map to the token.</param>
/// <param name="skipSpecialTokens">Indicate if want to skip the special tokens during the decoding.</param>
/// <returns>The mapped token of the Id.</returns>
public override string? IdToString(int id, bool skipSpecialTokens = false) => throw new NotImplementedException();

/// <summary>
/// Gets the dictionary mapping tokens to Ids.
/// </summary>
Expand DownExpand Up@@ -443,6 +451,11 @@ internal List<Token> TokenizeWithCache(string sequence)
return tokens;
}

public override bool IsValidChar(char ch)
{
throw new NotImplementedException();
}

internal static readonly List<Token> EmptyTokensList = new();
}
}
27 changes: 27 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/EnglishRoberta.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -135,6 +135,28 @@ public EnglishRoberta(Stream vocabularyStream, Stream mergeStream, Stream highes
public override string? IdToToken(int id, bool skipSpecialTokens = false) =>
skipSpecialTokens && id < 0 ? null : _vocabReverse.TryGetValue(id, out var value) ? value : null;

/// <summary>
/// Map the tokenized Id to the original string.
/// </summary>
/// <param name="id">The Id to map to the string.</param>
/// <param name="skipSpecialTokens">Indicate if want to skip the special tokens during the decoding.</param>
/// <returns>The mapped token of the Id.</returns>
public override string? IdToString(int id, bool skipSpecialTokens = false)
{
if (skipSpecialTokens && id < 0)
return null;
if (_vocabReverse.TryGetValue(id, out var value))
{
var textChars = string.Join("", value)
.Where(c => _unicodeToByte.ContainsKey(c))
.Select(c => _unicodeToByte[c]);
var text = new string(textChars.ToArray());
return text;
}

return null;
}

/// <summary>
/// Save the model data into the vocabulary, merges, and occurrence mapping files.
/// </summary>
Expand DownExpand Up@@ -565,6 +587,11 @@ private List<Token> BpeToken(Span<char> token, Span<int> indexMapping)

return pairs;
}

public override bool IsValidChar(char ch)
{
return _byteToUnicode.ContainsKey(ch);
}
}

/// <summary>
Expand Down
10 changes: 10 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/Model.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,8 @@ public abstract class Model
/// <returns>The mapped token of the Id.</returns>
public abstract string? IdToToken(int id, bool skipSpecialTokens = false);

public abstract string? IdToString(int id, bool skipSpecialTokens = false);

/// <summary>
/// Gets the dictionary mapping tokens to Ids.
/// </summary>
Expand All@@ -57,6 +59,14 @@ public abstract class Model
/// Gets a trainer object to use in training the model.
/// </summary>
public abstract Trainer? GetTrainer();

/// <summary>
/// Return true if the char is valid in the tokenizer; otherwise return false.
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
public abstract bool IsValidChar(char ch);

}

}
10 changes: 9 additions & 1 deletion src/Microsoft.ML.Tokenizers/Tokenizer.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -137,7 +137,10 @@ public TokenizerResult Encode(string sequence)

foreach (int id in ids)
{
tokens.Add(Model.IdToToken(id) ?? "");
if (Model.GetType() == typeof(EnglishRoberta))
tokens.Add(Model.IdToString(id) ?? "");
else
tokens.Add(Model.IdToToken(id) ?? "");
}

return Decoder?.Decode(tokens) ?? string.Join("", tokens);
Expand DownExpand Up@@ -187,5 +190,10 @@ public void TrainFromFiles(
// To Do: support added vocabulary in the tokenizer which will include this returned special_tokens.
// self.add_special_tokens(&special_tokens);
}

public bool IsValidChar(char ch)
{
return Model.IsValidChar(ch);
}
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,19 +17,12 @@
using static TorchSharp.torch.optim.lr_scheduler;
using Microsoft.ML.TorchSharp.Utils;
using Microsoft.ML;
using Microsoft.ML.TorchSharp.NasBert;
using System.IO;
using Microsoft.ML.Data.IO;
using Microsoft.ML.TorchSharp.Loss;
using Microsoft.ML.Transforms.Image;
using static Microsoft.ML.TorchSharp.AutoFormerV2.ObjectDetectionTrainer;
using Microsoft.ML.TorchSharp.AutoFormerV2;
using Microsoft.ML.Tokenizers;
using Microsoft.ML.TorchSharp.Extensions;
using Microsoft.ML.TorchSharp.NasBert.Models;
using static Microsoft.ML.TorchSharp.NasBert.NasBertTrainer;
using TorchSharp.Modules;
using System.Text;
using static Microsoft.ML.Data.AnnotationUtils;

[assembly: LoadableClass(typeof(ObjectDetectionTransformer), null, typeof(SignatureLoadModel),
Expand DownExpand Up@@ -503,7 +496,7 @@ private void CheckInputSchema(SchemaShape inputSchema)
}
}

public class ObjectDetectionTransformer : RowToRowTransformerBase
public class ObjectDetectionTransformer : RowToRowTransformerBase, IDisposable
{
private protected readonly Device Device;
private protected readonly AutoFormerV2 Model;
Expand All@@ -522,6 +515,7 @@ public class ObjectDetectionTransformer : RowToRowTransformerBase

private static readonly FuncStaticMethodInfo1<object, Delegate> _decodeInitMethodInfo
= new FuncStaticMethodInfo1<object, Delegate>(DecodeInit<int>);
private bool _disposedValue;

internal ObjectDetectionTransformer(IHostEnvironment env, ObjectDetectionTrainer.Options options, AutoFormerV2 model, DataViewSchema.DetachedColumn labelColumn)
: base(Contracts.CheckRef(env, nameof(env)).Register(nameof(ObjectDetectionTransformer)))
Expand DownExpand Up@@ -992,5 +986,31 @@ private protected override Func<int, bool> GetDependenciesCore(Func<int, bool> a
return col => (activeOutput(0) || activeOutput(1) || activeOutput(2)) && _inputColIndices.Any(i => i == col);
}
}

protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
}

Model.Dispose();
_disposedValue = true;
}
}

~ObjectDetectionTransformer()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: false);
}

public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
16 changes: 16 additions & 0 deletions src/Microsoft.ML.TorchSharp/NasBert/BertModelType.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Text;

namespace Microsoft.ML.TorchSharp.NasBert
{
internal enum BertModelType
{
NasBert,
Roberta
}
}
4 changes: 3 additions & 1 deletion src/Microsoft.ML.TorchSharp/NasBert/BertTaskType.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,8 @@ public enum BertTaskType
None = 0,
MaskedLM = 1,
TextClassification = 2,
SentenceRegression = 3
SentenceRegression = 3,
NameEntityRecognition = 4,
QuestionAnswering = 5
}
}
3 changes: 0 additions & 3 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/BaseHead.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,9 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Text;
using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
Expand Down
11 changes: 5 additions & 6 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/BaseModel.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,23 +3,22 @@
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ML.TorchSharp.Utils;
using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
{
internal abstract class BaseModel : torch.nn.Module<torch.Tensor, torch.Tensor, torch.Tensor>
{
protected readonly NasBertTrainer.NasBertOptions Options;
public BertTaskType HeadType => Options.TaskType;
public BertModelType EncoderType => Options.ModelType;

//public ModelType EncoderType => Options.ModelType;
public BertTaskType HeadType => Options.TaskType;

#pragma warning disable CA1024 // Use properties where appropriate: Modules should be fields in TorchSharp
public abstract TransformerEncoder GetEncoder();

public abstract BaseHead GetHead();

#pragma warning restore CA1024 // Use properties where appropriate

protected BaseModel(NasBertTrainer.NasBertOptions options)
Expand Down
36 changes: 36 additions & 0 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/ModelPrediction.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
{
internal sealed class ModelForPrediction : NasBertModel

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

NERInferenceModel?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

This isn't for NER. Its for SentenceSimilarity and TextClassification. How about TextModel? TextModelForPrediction? Thoughts?

{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_PrivateFieldName:Private field name not in: _camelCase format", Justification = "Has to match TorchSharp model.")]
private readonly PredictionHead PredictionHead;
Comment thread
JakeRadMSFT marked this conversation as resolved.

public override BaseHead GetHead() => PredictionHead;

public ModelForPrediction(NasBertTrainer.NasBertOptions options, int padIndex, int symbolsCount, int numClasses)
: base(options, padIndex, symbolsCount)
{
PredictionHead = new PredictionHead(
inputDim: Options.EncoderOutputDim,
numClasses: numClasses,
dropoutRate: Options.PoolerDropout);
Initialize();
RegisterComponents();
}

[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_GeneralName:This name should be PascalCased", Justification = "Need to match TorchSharp.")]
public override torch.Tensor forward(torch.Tensor srcTokens, torch.Tensor tokenMask = null)
{
using var disposeScope = torch.NewDisposeScope();
var x = ExtractFeatures(srcTokens);
x = PredictionHead.call(x);
return x.MoveToOuterDisposeScope();
}
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion build/ci/job-template.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,7 +68,7 @@ jobs:
steps:
# Extra MacOS step required to install OS-specific dependencies
- ${{ if and(contains(parameters.pool.vmImage, 'macOS'), not(contains(parameters.name, 'cross'))) }}:
- script: export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=TRUE && brew update && brew unlink libomp && brew install $(Build.SourcesDirectory)/build/libomp.rb --build-from-source --formula
- script: export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=TRUE && brew unlink libomp && brew install $(Build.SourcesDirectory)/build/libomp.rb --build-from-source --formula
displayName: Install MacOS build dependencies
# Extra Apple MacOS step required to install OS-specific dependencies
- ${{ if and(contains(parameters.pool.vmImage, 'macOS'), contains(parameters.name, 'cross')) }}:
Expand Down
13 changes: 13 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/BPE.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -195,6 +195,14 @@ public override IReadOnlyList<Token> Tokenize(string sequence)
return null;
}

/// <summary>
/// Map the tokenized Id to the token.
/// </summary>
/// <param name="id">The Id to map to the token.</param>
/// <param name="skipSpecialTokens">Indicate if want to skip the special tokens during the decoding.</param>
/// <returns>The mapped token of the Id.</returns>
public override string? IdToString(int id, bool skipSpecialTokens = false) => throw new NotImplementedException();

/// <summary>
/// Gets the dictionary mapping tokens to Ids.
/// </summary>
Expand DownExpand Up@@ -443,6 +451,11 @@ internal List<Token> TokenizeWithCache(string sequence)
return tokens;
}

public override bool IsValidChar(char ch)
{
throw new NotImplementedException();
}

internal static readonly List<Token> EmptyTokensList = new();
}
}
27 changes: 27 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/EnglishRoberta.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -135,6 +135,28 @@ public EnglishRoberta(Stream vocabularyStream, Stream mergeStream, Stream highes
public override string? IdToToken(int id, bool skipSpecialTokens = false) =>
skipSpecialTokens && id < 0 ? null : _vocabReverse.TryGetValue(id, out var value) ? value : null;

/// <summary>
/// Map the tokenized Id to the original string.
/// </summary>
/// <param name="id">The Id to map to the string.</param>
/// <param name="skipSpecialTokens">Indicate if want to skip the special tokens during the decoding.</param>
/// <returns>The mapped token of the Id.</returns>
public override string? IdToString(int id, bool skipSpecialTokens = false)
{
if (skipSpecialTokens && id < 0)
return null;
if (_vocabReverse.TryGetValue(id, out var value))
{
var textChars = string.Join("", value)
.Where(c => _unicodeToByte.ContainsKey(c))
.Select(c => _unicodeToByte[c]);
var text = new string(textChars.ToArray());
return text;
}

return null;
}

/// <summary>
/// Save the model data into the vocabulary, merges, and occurrence mapping files.
/// </summary>
Expand DownExpand Up@@ -565,6 +587,11 @@ private List<Token> BpeToken(Span<char> token, Span<int> indexMapping)

return pairs;
}

public override bool IsValidChar(char ch)
{
return _byteToUnicode.ContainsKey(ch);
}
}

/// <summary>
Expand Down
10 changes: 10 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/Model.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,8 @@ public abstract class Model
/// <returns>The mapped token of the Id.</returns>
public abstract string? IdToToken(int id, bool skipSpecialTokens = false);

public abstract string? IdToString(int id, bool skipSpecialTokens = false);

/// <summary>
/// Gets the dictionary mapping tokens to Ids.
/// </summary>
Expand All@@ -57,6 +59,14 @@ public abstract class Model
/// Gets a trainer object to use in training the model.
/// </summary>
public abstract Trainer? GetTrainer();

/// <summary>
/// Return true if the char is valid in the tokenizer; otherwise return false.
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
public abstract bool IsValidChar(char ch);

}

}
10 changes: 9 additions & 1 deletion src/Microsoft.ML.Tokenizers/Tokenizer.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -137,7 +137,10 @@ public TokenizerResult Encode(string sequence)

foreach (int id in ids)
{
tokens.Add(Model.IdToToken(id) ?? "");
if (Model.GetType() == typeof(EnglishRoberta))
tokens.Add(Model.IdToString(id) ?? "");
else
tokens.Add(Model.IdToToken(id) ?? "");
}

return Decoder?.Decode(tokens) ?? string.Join("", tokens);
Expand DownExpand Up@@ -187,5 +190,10 @@ public void TrainFromFiles(
// To Do: support added vocabulary in the tokenizer which will include this returned special_tokens.
// self.add_special_tokens(&special_tokens);
}

public bool IsValidChar(char ch)
{
return Model.IsValidChar(ch);
}
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,19 +17,12 @@
using static TorchSharp.torch.optim.lr_scheduler;
using Microsoft.ML.TorchSharp.Utils;
using Microsoft.ML;
using Microsoft.ML.TorchSharp.NasBert;
using System.IO;
using Microsoft.ML.Data.IO;
using Microsoft.ML.TorchSharp.Loss;
using Microsoft.ML.Transforms.Image;
using static Microsoft.ML.TorchSharp.AutoFormerV2.ObjectDetectionTrainer;
using Microsoft.ML.TorchSharp.AutoFormerV2;
using Microsoft.ML.Tokenizers;
using Microsoft.ML.TorchSharp.Extensions;
using Microsoft.ML.TorchSharp.NasBert.Models;
using static Microsoft.ML.TorchSharp.NasBert.NasBertTrainer;
using TorchSharp.Modules;
using System.Text;
using static Microsoft.ML.Data.AnnotationUtils;

[assembly: LoadableClass(typeof(ObjectDetectionTransformer), null, typeof(SignatureLoadModel),
Expand DownExpand Up@@ -503,7 +496,7 @@ private void CheckInputSchema(SchemaShape inputSchema)
}
}

public class ObjectDetectionTransformer : RowToRowTransformerBase
public class ObjectDetectionTransformer : RowToRowTransformerBase, IDisposable
{
private protected readonly Device Device;
private protected readonly AutoFormerV2 Model;
Expand All@@ -522,6 +515,7 @@ public class ObjectDetectionTransformer : RowToRowTransformerBase

private static readonly FuncStaticMethodInfo1<object, Delegate> _decodeInitMethodInfo
= new FuncStaticMethodInfo1<object, Delegate>(DecodeInit<int>);
private bool _disposedValue;

internal ObjectDetectionTransformer(IHostEnvironment env, ObjectDetectionTrainer.Options options, AutoFormerV2 model, DataViewSchema.DetachedColumn labelColumn)
: base(Contracts.CheckRef(env, nameof(env)).Register(nameof(ObjectDetectionTransformer)))
Expand DownExpand Up@@ -992,5 +986,31 @@ private protected override Func<int, bool> GetDependenciesCore(Func<int, bool> a
return col => (activeOutput(0) || activeOutput(1) || activeOutput(2)) && _inputColIndices.Any(i => i == col);
}
}

protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
}

Model.Dispose();
_disposedValue = true;
}
}

~ObjectDetectionTransformer()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: false);
}

public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
16 changes: 16 additions & 0 deletions src/Microsoft.ML.TorchSharp/NasBert/BertModelType.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Text;

namespace Microsoft.ML.TorchSharp.NasBert
{
internal enum BertModelType
{
NasBert,
Roberta
}
}
4 changes: 3 additions & 1 deletion src/Microsoft.ML.TorchSharp/NasBert/BertTaskType.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,8 @@ public enum BertTaskType
None = 0,
MaskedLM = 1,
TextClassification = 2,
SentenceRegression = 3
SentenceRegression = 3,
NameEntityRecognition = 4,
QuestionAnswering = 5
}
}
3 changes: 0 additions & 3 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/BaseHead.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,9 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Text;
using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
Expand Down
11 changes: 5 additions & 6 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/BaseModel.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,23 +3,22 @@
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ML.TorchSharp.Utils;
using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
{
internal abstract class BaseModel : torch.nn.Module<torch.Tensor, torch.Tensor, torch.Tensor>
{
protected readonly NasBertTrainer.NasBertOptions Options;
public BertTaskType HeadType => Options.TaskType;
public BertModelType EncoderType => Options.ModelType;

//public ModelType EncoderType => Options.ModelType;
public BertTaskType HeadType => Options.TaskType;

#pragma warning disable CA1024 // Use properties where appropriate: Modules should be fields in TorchSharp
public abstract TransformerEncoder GetEncoder();

public abstract BaseHead GetHead();

#pragma warning restore CA1024 // Use properties where appropriate

protected BaseModel(NasBertTrainer.NasBertOptions options)
Expand Down
36 changes: 36 additions & 0 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/ModelPrediction.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
{
internal sealed class ModelForPrediction : NasBertModel

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

NERInferenceModel?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

This isn't for NER. Its for SentenceSimilarity and TextClassification. How about TextModel? TextModelForPrediction? Thoughts?

{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_PrivateFieldName:Private field name not in: _camelCase format", Justification = "Has to match TorchSharp model.")]
private readonly PredictionHead PredictionHead;
Comment thread
JakeRadMSFT marked this conversation as resolved.

public override BaseHead GetHead() => PredictionHead;

public ModelForPrediction(NasBertTrainer.NasBertOptions options, int padIndex, int symbolsCount, int numClasses)
: base(options, padIndex, symbolsCount)
{
PredictionHead = new PredictionHead(
inputDim: Options.EncoderOutputDim,
numClasses: numClasses,
dropoutRate: Options.PoolerDropout);
Initialize();
RegisterComponents();
}

[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_GeneralName:This name should be PascalCased", Justification = "Need to match TorchSharp.")]
public override torch.Tensor forward(torch.Tensor srcTokens, torch.Tensor tokenMask = null)
{
using var disposeScope = torch.NewDisposeScope();
var x = ExtractFeatures(srcTokens);
x = PredictionHead.call(x);
return x.MoveToOuterDisposeScope();
}
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion build/ci/job-template.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,7 +68,7 @@ jobs:
steps:
# Extra MacOS step required to install OS-specific dependencies
- ${{ if and(contains(parameters.pool.vmImage, 'macOS'), not(contains(parameters.name, 'cross'))) }}:
- script: export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=TRUE && brew update && brew unlink libomp && brew install $(Build.SourcesDirectory)/build/libomp.rb --build-from-source --formula
- script: export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=TRUE && brew unlink libomp && brew install $(Build.SourcesDirectory)/build/libomp.rb --build-from-source --formula
displayName: Install MacOS build dependencies
# Extra Apple MacOS step required to install OS-specific dependencies
- ${{ if and(contains(parameters.pool.vmImage, 'macOS'), contains(parameters.name, 'cross')) }}:
Expand Down
13 changes: 13 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/BPE.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -195,6 +195,14 @@ public override IReadOnlyList<Token> Tokenize(string sequence)
return null;
}

/// <summary>
/// Map the tokenized Id to the token.
/// </summary>
/// <param name="id">The Id to map to the token.</param>
/// <param name="skipSpecialTokens">Indicate if want to skip the special tokens during the decoding.</param>
/// <returns>The mapped token of the Id.</returns>
public override string? IdToString(int id, bool skipSpecialTokens = false) => throw new NotImplementedException();

/// <summary>
/// Gets the dictionary mapping tokens to Ids.
/// </summary>
Expand DownExpand Up@@ -443,6 +451,11 @@ internal List<Token> TokenizeWithCache(string sequence)
return tokens;
}

public override bool IsValidChar(char ch)
{
throw new NotImplementedException();
}

internal static readonly List<Token> EmptyTokensList = new();
}
}
27 changes: 27 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/EnglishRoberta.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -135,6 +135,28 @@ public EnglishRoberta(Stream vocabularyStream, Stream mergeStream, Stream highes
public override string? IdToToken(int id, bool skipSpecialTokens = false) =>
skipSpecialTokens && id < 0 ? null : _vocabReverse.TryGetValue(id, out var value) ? value : null;

/// <summary>
/// Map the tokenized Id to the original string.
/// </summary>
/// <param name="id">The Id to map to the string.</param>
/// <param name="skipSpecialTokens">Indicate if want to skip the special tokens during the decoding.</param>
/// <returns>The mapped token of the Id.</returns>
public override string? IdToString(int id, bool skipSpecialTokens = false)
{
if (skipSpecialTokens && id < 0)
return null;
if (_vocabReverse.TryGetValue(id, out var value))
{
var textChars = string.Join("", value)
.Where(c => _unicodeToByte.ContainsKey(c))
.Select(c => _unicodeToByte[c]);
var text = new string(textChars.ToArray());
return text;
}

return null;
}

/// <summary>
/// Save the model data into the vocabulary, merges, and occurrence mapping files.
/// </summary>
Expand DownExpand Up@@ -565,6 +587,11 @@ private List<Token> BpeToken(Span<char> token, Span<int> indexMapping)

return pairs;
}

public override bool IsValidChar(char ch)
{
return _byteToUnicode.ContainsKey(ch);
}
}

/// <summary>
Expand Down
10 changes: 10 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/Model.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,8 @@ public abstract class Model
/// <returns>The mapped token of the Id.</returns>
public abstract string? IdToToken(int id, bool skipSpecialTokens = false);

public abstract string? IdToString(int id, bool skipSpecialTokens = false);

/// <summary>
/// Gets the dictionary mapping tokens to Ids.
/// </summary>
Expand All@@ -57,6 +59,14 @@ public abstract class Model
/// Gets a trainer object to use in training the model.
/// </summary>
public abstract Trainer? GetTrainer();

/// <summary>
/// Return true if the char is valid in the tokenizer; otherwise return false.
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
public abstract bool IsValidChar(char ch);

}

}
10 changes: 9 additions & 1 deletion src/Microsoft.ML.Tokenizers/Tokenizer.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -137,7 +137,10 @@ public TokenizerResult Encode(string sequence)

foreach (int id in ids)
{
tokens.Add(Model.IdToToken(id) ?? "");
if (Model.GetType() == typeof(EnglishRoberta))
tokens.Add(Model.IdToString(id) ?? "");
else
tokens.Add(Model.IdToToken(id) ?? "");
}

return Decoder?.Decode(tokens) ?? string.Join("", tokens);
Expand DownExpand Up@@ -187,5 +190,10 @@ public void TrainFromFiles(
// To Do: support added vocabulary in the tokenizer which will include this returned special_tokens.
// self.add_special_tokens(&special_tokens);
}

public bool IsValidChar(char ch)
{
return Model.IsValidChar(ch);
}
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,19 +17,12 @@
using static TorchSharp.torch.optim.lr_scheduler;
using Microsoft.ML.TorchSharp.Utils;
using Microsoft.ML;
using Microsoft.ML.TorchSharp.NasBert;
using System.IO;
using Microsoft.ML.Data.IO;
using Microsoft.ML.TorchSharp.Loss;
using Microsoft.ML.Transforms.Image;
using static Microsoft.ML.TorchSharp.AutoFormerV2.ObjectDetectionTrainer;
using Microsoft.ML.TorchSharp.AutoFormerV2;
using Microsoft.ML.Tokenizers;
using Microsoft.ML.TorchSharp.Extensions;
using Microsoft.ML.TorchSharp.NasBert.Models;
using static Microsoft.ML.TorchSharp.NasBert.NasBertTrainer;
using TorchSharp.Modules;
using System.Text;
using static Microsoft.ML.Data.AnnotationUtils;

[assembly: LoadableClass(typeof(ObjectDetectionTransformer), null, typeof(SignatureLoadModel),
Expand DownExpand Up@@ -503,7 +496,7 @@ private void CheckInputSchema(SchemaShape inputSchema)
}
}

public class ObjectDetectionTransformer : RowToRowTransformerBase
public class ObjectDetectionTransformer : RowToRowTransformerBase, IDisposable
{
private protected readonly Device Device;
private protected readonly AutoFormerV2 Model;
Expand All@@ -522,6 +515,7 @@ public class ObjectDetectionTransformer : RowToRowTransformerBase

private static readonly FuncStaticMethodInfo1<object, Delegate> _decodeInitMethodInfo
= new FuncStaticMethodInfo1<object, Delegate>(DecodeInit<int>);
private bool _disposedValue;

internal ObjectDetectionTransformer(IHostEnvironment env, ObjectDetectionTrainer.Options options, AutoFormerV2 model, DataViewSchema.DetachedColumn labelColumn)
: base(Contracts.CheckRef(env, nameof(env)).Register(nameof(ObjectDetectionTransformer)))
Expand DownExpand Up@@ -992,5 +986,31 @@ private protected override Func<int, bool> GetDependenciesCore(Func<int, bool> a
return col => (activeOutput(0) || activeOutput(1) || activeOutput(2)) && _inputColIndices.Any(i => i == col);
}
}

protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
}

Model.Dispose();
_disposedValue = true;
}
}

~ObjectDetectionTransformer()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: false);
}

public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
16 changes: 16 additions & 0 deletions src/Microsoft.ML.TorchSharp/NasBert/BertModelType.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Text;

namespace Microsoft.ML.TorchSharp.NasBert
{
internal enum BertModelType
{
NasBert,
Roberta
}
}
4 changes: 3 additions & 1 deletion src/Microsoft.ML.TorchSharp/NasBert/BertTaskType.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,8 @@ public enum BertTaskType
None = 0,
MaskedLM = 1,
TextClassification = 2,
SentenceRegression = 3
SentenceRegression = 3,
NameEntityRecognition = 4,
QuestionAnswering = 5
}
}
3 changes: 0 additions & 3 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/BaseHead.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,9 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Text;
using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
Expand Down
11 changes: 5 additions & 6 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/BaseModel.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,23 +3,22 @@
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ML.TorchSharp.Utils;
using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
{
internal abstract class BaseModel : torch.nn.Module<torch.Tensor, torch.Tensor, torch.Tensor>
{
protected readonly NasBertTrainer.NasBertOptions Options;
public BertTaskType HeadType => Options.TaskType;
public BertModelType EncoderType => Options.ModelType;

//public ModelType EncoderType => Options.ModelType;
public BertTaskType HeadType => Options.TaskType;

#pragma warning disable CA1024 // Use properties where appropriate: Modules should be fields in TorchSharp
public abstract TransformerEncoder GetEncoder();

public abstract BaseHead GetHead();

#pragma warning restore CA1024 // Use properties where appropriate

protected BaseModel(NasBertTrainer.NasBertOptions options)
Expand Down
36 changes: 36 additions & 0 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/ModelPrediction.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
{
internal sealed class ModelForPrediction : NasBertModel

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

NERInferenceModel?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

This isn't for NER. Its for SentenceSimilarity and TextClassification. How about TextModel? TextModelForPrediction? Thoughts?

{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_PrivateFieldName:Private field name not in: _camelCase format", Justification = "Has to match TorchSharp model.")]
private readonly PredictionHead PredictionHead;
Comment thread
JakeRadMSFT marked this conversation as resolved.

public override BaseHead GetHead() => PredictionHead;

public ModelForPrediction(NasBertTrainer.NasBertOptions options, int padIndex, int symbolsCount, int numClasses)
: base(options, padIndex, symbolsCount)
{
PredictionHead = new PredictionHead(
inputDim: Options.EncoderOutputDim,
numClasses: numClasses,
dropoutRate: Options.PoolerDropout);
Initialize();
RegisterComponents();
}

[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_GeneralName:This name should be PascalCased", Justification = "Need to match TorchSharp.")]
public override torch.Tensor forward(torch.Tensor srcTokens, torch.Tensor tokenMask = null)
{
using var disposeScope = torch.NewDisposeScope();
var x = ExtractFeatures(srcTokens);
x = PredictionHead.call(x);
return x.MoveToOuterDisposeScope();
}
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion build/ci/job-template.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,7 +68,7 @@ jobs:
steps:
# Extra MacOS step required to install OS-specific dependencies
- ${{ if and(contains(parameters.pool.vmImage, 'macOS'), not(contains(parameters.name, 'cross'))) }}:
- script: export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=TRUE && brew update && brew unlink libomp && brew install $(Build.SourcesDirectory)/build/libomp.rb --build-from-source --formula
- script: export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=TRUE && brew unlink libomp && brew install $(Build.SourcesDirectory)/build/libomp.rb --build-from-source --formula
displayName: Install MacOS build dependencies
# Extra Apple MacOS step required to install OS-specific dependencies
- ${{ if and(contains(parameters.pool.vmImage, 'macOS'), contains(parameters.name, 'cross')) }}:
Expand Down
13 changes: 13 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/BPE.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -195,6 +195,14 @@ public override IReadOnlyList<Token> Tokenize(string sequence)
return null;
}

/// <summary>
/// Map the tokenized Id to the token.
/// </summary>
/// <param name="id">The Id to map to the token.</param>
/// <param name="skipSpecialTokens">Indicate if want to skip the special tokens during the decoding.</param>
/// <returns>The mapped token of the Id.</returns>
public override string? IdToString(int id, bool skipSpecialTokens = false) => throw new NotImplementedException();

/// <summary>
/// Gets the dictionary mapping tokens to Ids.
/// </summary>
Expand DownExpand Up@@ -443,6 +451,11 @@ internal List<Token> TokenizeWithCache(string sequence)
return tokens;
}

public override bool IsValidChar(char ch)
{
throw new NotImplementedException();
}

internal static readonly List<Token> EmptyTokensList = new();
}
}
27 changes: 27 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/EnglishRoberta.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -135,6 +135,28 @@ public EnglishRoberta(Stream vocabularyStream, Stream mergeStream, Stream highes
public override string? IdToToken(int id, bool skipSpecialTokens = false) =>
skipSpecialTokens && id < 0 ? null : _vocabReverse.TryGetValue(id, out var value) ? value : null;

/// <summary>
/// Map the tokenized Id to the original string.
/// </summary>
/// <param name="id">The Id to map to the string.</param>
/// <param name="skipSpecialTokens">Indicate if want to skip the special tokens during the decoding.</param>
/// <returns>The mapped token of the Id.</returns>
public override string? IdToString(int id, bool skipSpecialTokens = false)
{
if (skipSpecialTokens && id < 0)
return null;
if (_vocabReverse.TryGetValue(id, out var value))
{
var textChars = string.Join("", value)
.Where(c => _unicodeToByte.ContainsKey(c))
.Select(c => _unicodeToByte[c]);
var text = new string(textChars.ToArray());
return text;
}

return null;
}

/// <summary>
/// Save the model data into the vocabulary, merges, and occurrence mapping files.
/// </summary>
Expand DownExpand Up@@ -565,6 +587,11 @@ private List<Token> BpeToken(Span<char> token, Span<int> indexMapping)

return pairs;
}

public override bool IsValidChar(char ch)
{
return _byteToUnicode.ContainsKey(ch);
}
}

/// <summary>
Expand Down
10 changes: 10 additions & 0 deletions src/Microsoft.ML.Tokenizers/Model/Model.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,8 @@ public abstract class Model
/// <returns>The mapped token of the Id.</returns>
public abstract string? IdToToken(int id, bool skipSpecialTokens = false);

public abstract string? IdToString(int id, bool skipSpecialTokens = false);

/// <summary>
/// Gets the dictionary mapping tokens to Ids.
/// </summary>
Expand All@@ -57,6 +59,14 @@ public abstract class Model
/// Gets a trainer object to use in training the model.
/// </summary>
public abstract Trainer? GetTrainer();

/// <summary>
/// Return true if the char is valid in the tokenizer; otherwise return false.
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
public abstract bool IsValidChar(char ch);

}

}
10 changes: 9 additions & 1 deletion src/Microsoft.ML.Tokenizers/Tokenizer.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -137,7 +137,10 @@ public TokenizerResult Encode(string sequence)

foreach (int id in ids)
{
tokens.Add(Model.IdToToken(id) ?? "");
if (Model.GetType() == typeof(EnglishRoberta))
tokens.Add(Model.IdToString(id) ?? "");
else
tokens.Add(Model.IdToToken(id) ?? "");
}

return Decoder?.Decode(tokens) ?? string.Join("", tokens);
Expand DownExpand Up@@ -187,5 +190,10 @@ public void TrainFromFiles(
// To Do: support added vocabulary in the tokenizer which will include this returned special_tokens.
// self.add_special_tokens(&special_tokens);
}

public bool IsValidChar(char ch)
{
return Model.IsValidChar(ch);
}
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,19 +17,12 @@
using static TorchSharp.torch.optim.lr_scheduler;
using Microsoft.ML.TorchSharp.Utils;
using Microsoft.ML;
using Microsoft.ML.TorchSharp.NasBert;
using System.IO;
using Microsoft.ML.Data.IO;
using Microsoft.ML.TorchSharp.Loss;
using Microsoft.ML.Transforms.Image;
using static Microsoft.ML.TorchSharp.AutoFormerV2.ObjectDetectionTrainer;
using Microsoft.ML.TorchSharp.AutoFormerV2;
using Microsoft.ML.Tokenizers;
using Microsoft.ML.TorchSharp.Extensions;
using Microsoft.ML.TorchSharp.NasBert.Models;
using static Microsoft.ML.TorchSharp.NasBert.NasBertTrainer;
using TorchSharp.Modules;
using System.Text;
using static Microsoft.ML.Data.AnnotationUtils;

[assembly: LoadableClass(typeof(ObjectDetectionTransformer), null, typeof(SignatureLoadModel),
Expand DownExpand Up@@ -503,7 +496,7 @@ private void CheckInputSchema(SchemaShape inputSchema)
}
}

public class ObjectDetectionTransformer : RowToRowTransformerBase
public class ObjectDetectionTransformer : RowToRowTransformerBase, IDisposable
{
private protected readonly Device Device;
private protected readonly AutoFormerV2 Model;
Expand All@@ -522,6 +515,7 @@ public class ObjectDetectionTransformer : RowToRowTransformerBase

private static readonly FuncStaticMethodInfo1<object, Delegate> _decodeInitMethodInfo
= new FuncStaticMethodInfo1<object, Delegate>(DecodeInit<int>);
private bool _disposedValue;

internal ObjectDetectionTransformer(IHostEnvironment env, ObjectDetectionTrainer.Options options, AutoFormerV2 model, DataViewSchema.DetachedColumn labelColumn)
: base(Contracts.CheckRef(env, nameof(env)).Register(nameof(ObjectDetectionTransformer)))
Expand DownExpand Up@@ -992,5 +986,31 @@ private protected override Func<int, bool> GetDependenciesCore(Func<int, bool> a
return col => (activeOutput(0) || activeOutput(1) || activeOutput(2)) && _inputColIndices.Any(i => i == col);
}
}

protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
}

Model.Dispose();
_disposedValue = true;
}
}

~ObjectDetectionTransformer()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: false);
}

public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
16 changes: 16 additions & 0 deletions src/Microsoft.ML.TorchSharp/NasBert/BertModelType.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Text;

namespace Microsoft.ML.TorchSharp.NasBert
{
internal enum BertModelType
{
NasBert,
Roberta
}
}
4 changes: 3 additions & 1 deletion src/Microsoft.ML.TorchSharp/NasBert/BertTaskType.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,8 @@ public enum BertTaskType
None = 0,
MaskedLM = 1,
TextClassification = 2,
SentenceRegression = 3
SentenceRegression = 3,
NameEntityRecognition = 4,
QuestionAnswering = 5
}
}
3 changes: 0 additions & 3 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/BaseHead.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,9 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Text;
using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
Expand Down
11 changes: 5 additions & 6 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/BaseModel.cs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,23 +3,22 @@
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ML.TorchSharp.Utils;
using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
{
internal abstract class BaseModel : torch.nn.Module<torch.Tensor, torch.Tensor, torch.Tensor>
{
protected readonly NasBertTrainer.NasBertOptions Options;
public BertTaskType HeadType => Options.TaskType;
public BertModelType EncoderType => Options.ModelType;

//public ModelType EncoderType => Options.ModelType;
public BertTaskType HeadType => Options.TaskType;

#pragma warning disable CA1024 // Use properties where appropriate: Modules should be fields in TorchSharp
public abstract TransformerEncoder GetEncoder();

public abstract BaseHead GetHead();

#pragma warning restore CA1024 // Use properties where appropriate

protected BaseModel(NasBertTrainer.NasBertOptions options)
Expand Down
36 changes: 36 additions & 0 deletions src/Microsoft.ML.TorchSharp/NasBert/Models/ModelPrediction.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using TorchSharp;

namespace Microsoft.ML.TorchSharp.NasBert.Models
{
internal sealed class ModelForPrediction : NasBertModel

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

NERInferenceModel?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

This isn't for NER. Its for SentenceSimilarity and TextClassification. How about TextModel? TextModelForPrediction? Thoughts?

{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_PrivateFieldName:Private field name not in: _camelCase format", Justification = "Has to match TorchSharp model.")]
private readonly PredictionHead PredictionHead;
Comment thread
JakeRadMSFT marked this conversation as resolved.

public override BaseHead GetHead() => PredictionHead;

public ModelForPrediction(NasBertTrainer.NasBertOptions options, int padIndex, int symbolsCount, int numClasses)
: base(options, padIndex, symbolsCount)
{
PredictionHead = new PredictionHead(
inputDim: Options.EncoderOutputDim,
numClasses: numClasses,
dropoutRate: Options.PoolerDropout);
Initialize();
RegisterComponents();
}

[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "MSML_GeneralName:This name should be PascalCased", Justification = "Need to match TorchSharp.")]
public override torch.Tensor forward(torch.Tensor srcTokens, torch.Tensor tokenMask = null)
{
using var disposeScope = torch.NewDisposeScope();
var x = ExtractFeatures(srcTokens);
x = PredictionHead.call(x);
return x.MoveToOuterDisposeScope();
}
}
}
Loading