Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 1.9k
Fixes NER to correctly expand/shrink the labels#6928
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Uh oh!
There was an error while loading. Please reload this page.
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -19,6 +19,7 @@ | ||
| using Microsoft.ML.TorchSharp.NasBert.Models; | ||
| using TorchSharp; | ||
| using static Microsoft.ML.TorchSharp.NasBert.NasBertTrainer; | ||
| using static TorchSharp.torch; | ||
| [assembly: LoadableClass(typeof(NerTransformer), null, typeof(SignatureLoadModel), | ||
| NerTransformer.UserName, NerTransformer.LoaderSignature)] | ||
| @@ -61,6 +62,8 @@ namespace Microsoft.ML.TorchSharp.NasBert | ||
| /// | ||
| public class NerTrainer : NasBertTrainer<VBuffer<uint>, TargetType> | ||
| { | ||
| private const char StartChar = (char)(' ' + 256); | ||
| public class NerOptions : NasBertOptions | ||
| { | ||
| public NerOptions() | ||
| @@ -69,6 +72,7 @@ public NerOptions() | ||
| EncoderOutputDim = 384; | ||
| EmbeddingDim = 128; | ||
| Arches = new int[] { 15, 16, 14, 0, 0, 0, 15, 16, 14, 0, 0, 0, 17, 14, 15, 0, 0, 0, 17, 14, 15, 0, 0, 0 }; | ||
| TaskType = BertTaskType.NamedEntityRecognition; | ||
| } | ||
| } | ||
| internal NerTrainer(IHostEnvironment env, NerOptions options) : base(env, options) | ||
| @@ -93,7 +97,6 @@ internal NerTrainer(IHostEnvironment env, | ||
| BatchSize = batchSize, | ||
| MaxEpoch = maxEpochs, | ||
| ValidationSet = validationSet, | ||
| TaskType = BertTaskType.NamedEntityRecognition | ||
| }) | ||
| { | ||
| } | ||
| @@ -108,9 +111,12 @@ private protected override TorchSharpBaseTransformer<VBuffer<uint>, TargetType> | ||
| return new NerTransformer(host, options as NasBertOptions, model as NasBertModel, labelColumn); | ||
| } | ||
| internal static bool TokenStartsWithSpace(string token) => token is null || (token.Length != 0 && token[0] == StartChar); | ||
| private protected class Trainer : NasBertTrainerBase | ||
| { | ||
| private const string ModelUrlString = "models/pretrained_NasBert_14M_encoder.tsm"; | ||
| internal static readonly int[] ZeroArray = new int[] { 0 /* InitToken */}; | ||
| public Trainer(TorchSharpBaseTrainer<VBuffer<uint>, TargetType> parent, IChannel ch, IDataView input) : base(parent, ch, input, ModelUrlString) | ||
| { | ||
| @@ -155,6 +161,40 @@ private protected override torch.Tensor CreateTargetsTensor(ref List<TargetType> | ||
| return torch.tensor(targetArray, device: Device); | ||
| } | ||
| private protected override torch.Tensor PrepareRowTensor(ref VBuffer<uint> target) | ||
| { | ||
| ReadOnlyMemory<char> sentenceRom = default; | ||
| Sentence1Getter(ref sentenceRom); | ||
| var sentence = sentenceRom.ToString(); | ||
| Tensor t; | ||
| var encoding = Tokenizer.Encode(sentence); | ||
| if (target.Length != encoding.Tokens.Count) | ||
| { | ||
| var targetIndex = 0; | ||
| var targetEditor = VBufferEditor.Create(ref target, encoding.Tokens.Count); | ||
| var newValues = targetEditor.Values; | ||
| for (var i = 0; i < encoding.Tokens.Count; i++) | ||
| { | ||
| if (NerTrainer.TokenStartsWithSpace(encoding.Tokens[i])) | ||
| { | ||
| newValues[i] = target.GetItemOrDefault(++targetIndex); | ||
| } | ||
| else | ||
| { | ||
| newValues[i] = target.GetItemOrDefault(targetIndex); | ||
| } | ||
| } | ||
| target = targetEditor.Commit(); | ||
| } | ||
| t = torch.tensor((ZeroArray).Concat(Tokenizer.RobertaModel().IdsToOccurrenceRanks(encoding.Ids)).ToList(), device: Device); | ||
| if (t.NumberOfElements > 512) | ||
| t = t.slice(0, 0, 512, 1); | ||
| return t; | ||
| } | ||
| [MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
| private protected override int GetNumCorrect(torch.Tensor predictions, torch.Tensor targets) | ||
| { | ||
| @@ -334,6 +374,41 @@ private protected override Delegate CreateGetter(DataViewRow input, int iinfo, T | ||
| } | ||
| private void CondenseOutput(ref VBuffer<UInt32> dst, string sentence, Tokenizer tokenizer, TensorCacher outputCacher) | ||
| { | ||
| var pre = tokenizer.PreTokenizer.PreTokenize(sentence); | ||
| TokenizerResult encoding = tokenizer.Encode(sentence); | ||
michaelgsharp marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| var argmax = (outputCacher as BertTensorCacher).Result.argmax(-1); | ||
| var prediction = argmax.ToArray<long>(); | ||
| var targetIndex = 0; | ||
| // Figure out actual count of output tokens | ||
| for (var i = 0; i < encoding.Tokens.Count; i++) | ||
| { | ||
| if (NerTrainer.TokenStartsWithSpace(encoding.Tokens[i])) | ||
| { | ||
| targetIndex++; | ||
| } | ||
| } | ||
| var editor = VBufferEditor.Create(ref dst, targetIndex + 1); | ||
| var newValues = editor.Values; | ||
| targetIndex = 0; | ||
| newValues[targetIndex++] = (uint)prediction[0]; | ||
| for (var i = 1; i < encoding.Tokens.Count; i++) | ||
| { | ||
| if (NerTrainer.TokenStartsWithSpace(encoding.Tokens[i])) | ||
| { | ||
| newValues[targetIndex++] = (uint)prediction[i]; | ||
| } | ||
| } | ||
| dst = editor.Commit(); | ||
| } | ||
| private Delegate MakePredictedLabelGetter(DataViewRow input, IChannel ch, TensorCacher outputCacher) | ||
| { | ||
| ValueGetter<ReadOnlyMemory<char>> getSentence1 = default; | ||
| @@ -353,13 +428,7 @@ private Delegate MakePredictedLabelGetter(DataViewRow input, IChannel ch, Tensor | ||
| var argmax = (outputCacher as BertTensorCacher).Result.argmax(-1); | ||
| var prediction = argmax.ToArray<long>(); | ||
| var editor = VBufferEditor.Create(ref dst, prediction.Length - 1); | ||
| for (int i = 1; i < prediction.Length; i++) | ||
| { | ||
| editor.Values[i - 1] = (uint)prediction[i]; | ||
| } | ||
| dst = editor.Commit(); | ||
| CondenseOutput(ref dst, sentence1.ToString(), tokenizer, outputCacher); | ||
| }; | ||
| return classification; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.