Read the tone of English headlines with the pinned ONNX model of SPEC 4.5 (refs #57)
ci / test (postgres) (push) Failing after 6m20s
ci / test (sqlite) (push) Failing after 5m59s
ci / image (push) Skipped
ci / test (postgres) (pull_request) Failing after 4m51s
ci / test (sqlite) (pull_request) Successful in 5m29s
ci / image (pull_request) Skipped

The classifier is distilroberta-finetuned-financial-news-sentiment-analysis in
Xenova's quantized ONNX export, pinned at revision e6953e30 and checked by size and
SHA-256.

- Model download: the model is not in the repository. The news job downloads it in
  the background into the models folder of the data directory, the first time, and
  retries after 6 hours if that fails. Until then the keywords judge alone, as
  SPEC 10.3 requires.
- Tokenizer: RoBERTa's byte-level BPE travels inside the DLL, read with
  BpeTokenizer and the RoBERTa pre-tokenizer. CodeGenTokenizer.Create adds ids for
  runs of spaces that the model rejects. No special tokens are recognised in
  untrusted text.
- Token check: the test compares the ids on 14 headlines with an independent copy
  of the GPT-2 encoder run on the same files.
- Model test: it reads the tone of clear headlines at 23-24 ms per title on one
  thread. It runs where the model is already downloaded and is skipped in CI.

Microsoft.ML.OnnxRuntime 1.31.1 and Microsoft.ML.Tokenizers 2.0.1 come from the
ADR 0004 list. Google.Protobuf joins the known indirect dependencies.

Anubis and Anubis.Server now declare win-x64 among their runtime identifiers, so
their lock files hold the Windows native packages. Publishing the Windows zip no
longer rewrites the lock files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-15 12:00:54 +01:00
1 parent 5f0ce6b172
commit 78e77818eb
21 files changed
+50715 -26

No files matched your search

+38
View File
@@ -2,6 +2,11 @@
"version": 2,
"dependencies": {
"net10.0-windows7.0": {
"Google.Protobuf": {
"type": "Transitive",
"resolved": "3.30.2",
"contentHash": "Y2aOVLIt75yeeEWigg9V9YnjsEm53sADtLGq0gLhwaXpk3iu8tYSoauolyhenagA2sWno2TQ2WujI0HQd6s1Vw=="
},
"Microsoft.Data.Sqlite.Core": {
"type": "Transitive",
"resolved": "10.0.14",
@@ -23,6 +28,14 @@
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0"
}
},
"Microsoft.ML.OnnxRuntime.Managed": {
"type": "Transitive",
"resolved": "1.31.1",
"contentHash": "158JCbNXN9/90LtjF4vHFiJYCF0bqF7CxLjm031jq7dJLEn/CtlHpMJm3UItQSIhQenlx+9Zuqi3zulwnsRVtA==",
"dependencies": {
"System.Numerics.Tensors": "9.0.0"
}
},
"SQLitePCLRaw.bundle_e_sqlite3": {
"type": "Transitive",
"resolved": "2.1.13",
@@ -50,10 +63,17 @@
"SQLitePCLRaw.core": "2.1.13"
}
},
"System.Numerics.Tensors": {
"type": "Transitive",
"resolved": "9.0.0",
"contentHash": "hyJB4UlpAi19Xr9AXzu2NuagKC4lPfHObNMEAA0HmqFz2rX7wKgzeYzO/jM/eBHDhnUGFFEjk5cOoJaxqg5J4A=="
},
"anubis": {
"type": "Project",
"dependencies": {
"Microsoft.Data.Sqlite": "[10.0.14, )",
"Microsoft.ML.OnnxRuntime": "[1.31.1, )",
"Microsoft.ML.Tokenizers": "[2.0.1, )",
"Npgsql": "[10.0.3, )",
"System.Security.Cryptography.ProtectedData": "[10.0.14, )"
}
@@ -69,6 +89,24 @@
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.ML.OnnxRuntime": {
"type": "CentralTransitive",
"requested": "[1.31.1, )",
"resolved": "1.31.1",
"contentHash": "XtsO/1JoKepkWbGk9/DcYtRUTduwJD68kw0eeaH5yy77YBivUZWhC1NBNlVecsBt9EitlQIjCd1hHDNXJ2jbQA==",
"dependencies": {
"Microsoft.ML.OnnxRuntime.Managed": "1.31.1"
}
},
"Microsoft.ML.Tokenizers": {
"type": "CentralTransitive",
"requested": "[2.0.1, )",
"resolved": "2.0.1",
"contentHash": "RZN3zslVWinBCMDAnbZWEY8lQbMkP54Yxm1s5NigPcrvYFzXMrDjNcVM9afq4SZHf1BV1rEmO0p7ZdfBLDbu4g==",
"dependencies": {
"Google.Protobuf": "3.30.2"
}
},
"Npgsql": {
"type": "CentralTransitive",
"requested": "[10.0.3, )",
+35 -13
View File
@@ -2,6 +2,11 @@
"version": 2,
"dependencies": {
"net10.0": {
"Google.Protobuf": {
"type": "Transitive",
"resolved": "3.30.2",
"contentHash": "Y2aOVLIt75yeeEWigg9V9YnjsEm53sADtLGq0gLhwaXpk3iu8tYSoauolyhenagA2sWno2TQ2WujI0HQd6s1Vw=="
},
"Microsoft.Data.Sqlite.Core": {
"type": "Transitive",
"resolved": "10.0.14",
@@ -10,17 +15,12 @@
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.Extensions.DependencyInjection.Abstractions": {
"Microsoft.ML.OnnxRuntime.Managed": {
"type": "Transitive",
"resolved": "10.0.0",
"contentHash": "L3AdmZ1WOK4XXT5YFPEwyt0ep6l8lGIPs7F5OOBZc77Zqeo01Of7XXICy47628sdVl0v/owxYJTe86DTgFwKCA=="
},
"Microsoft.Extensions.Logging.Abstractions": {
"type": "Transitive",
"resolved": "10.0.0",
"contentHash": "FU/IfjDfwaMuKr414SSQNTIti/69bHEMb+QKrskRb26oVqpx3lNFXMjs/RC9ZUuhBhcwDM2BwOgoMw+PZ+beqQ==",
"resolved": "1.31.1",
"contentHash": "158JCbNXN9/90LtjF4vHFiJYCF0bqF7CxLjm031jq7dJLEn/CtlHpMJm3UItQSIhQenlx+9Zuqi3zulwnsRVtA==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0"
"System.Numerics.Tensors": "9.0.0"
}
},
"SQLitePCLRaw.bundle_e_sqlite3": {
@@ -50,10 +50,17 @@
"SQLitePCLRaw.core": "2.1.13"
}
},
"System.Numerics.Tensors": {
"type": "Transitive",
"resolved": "9.0.0",
"contentHash": "hyJB4UlpAi19Xr9AXzu2NuagKC4lPfHObNMEAA0HmqFz2rX7wKgzeYzO/jM/eBHDhnUGFFEjk5cOoJaxqg5J4A=="
},
"anubis": {
"type": "Project",
"dependencies": {
"Microsoft.Data.Sqlite": "[10.0.14, )",
"Microsoft.ML.OnnxRuntime": "[1.31.1, )",
"Microsoft.ML.Tokenizers": "[2.0.1, )",
"Npgsql": "[10.0.3, )",
"System.Security.Cryptography.ProtectedData": "[10.0.14, )"
}
@@ -69,14 +76,29 @@
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.ML.OnnxRuntime": {
"type": "CentralTransitive",
"requested": "[1.31.1, )",
"resolved": "1.31.1",
"contentHash": "XtsO/1JoKepkWbGk9/DcYtRUTduwJD68kw0eeaH5yy77YBivUZWhC1NBNlVecsBt9EitlQIjCd1hHDNXJ2jbQA==",
"dependencies": {
"Microsoft.ML.OnnxRuntime.Managed": "1.31.1"
}
},
"Microsoft.ML.Tokenizers": {
"type": "CentralTransitive",
"requested": "[2.0.1, )",
"resolved": "2.0.1",
"contentHash": "RZN3zslVWinBCMDAnbZWEY8lQbMkP54Yxm1s5NigPcrvYFzXMrDjNcVM9afq4SZHf1BV1rEmO0p7ZdfBLDbu4g==",
"dependencies": {
"Google.Protobuf": "3.30.2"
}
},
"Npgsql": {
"type": "CentralTransitive",
"requested": "[10.0.3, )",
"resolved": "10.0.3",
"contentHash": "7nb5YzXuvWWJxB0J8DiyL3we+X4FOctZrt0fIBnucOIaIevFEEwGQVZKtiu9olXdlNAK1eNgqSral6r/jlhI4w==",
"dependencies": {
"Microsoft.Extensions.Logging.Abstractions": "10.0.0"
}
"contentHash": "7nb5YzXuvWWJxB0J8DiyL3we+X4FOctZrt0fIBnucOIaIevFEEwGQVZKtiu9olXdlNAK1eNgqSral6r/jlhI4w=="
},
"System.Security.Cryptography.ProtectedData": {
"type": "CentralTransitive",
+3
View File
@@ -4,6 +4,9 @@
<InvariantGlobalization>false</InvariantGlobalization>
<!-- Static rendering only: no blazor.web.js, so no Microsoft.AspNetCore.App.Internal.Assets package (ADR 0007). -->
<RequiresAspNetWebAssets>false</RequiresAspNetWebAssets>
<!-- The Windows trial zip is published for win-x64 (tasks release-win). Declared here, the lock file also holds the
native packages of that runtime (ONNX Runtime), so publishing never changes it. -->
<RuntimeIdentifiers>win-x64</RuntimeIdentifiers>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Anubis\Anubis.csproj" />
+54
View File
@@ -2,6 +2,11 @@
"version": 2,
"dependencies": {
"net10.0": {
"Google.Protobuf": {
"type": "Transitive",
"resolved": "3.30.2",
"contentHash": "Y2aOVLIt75yeeEWigg9V9YnjsEm53sADtLGq0gLhwaXpk3iu8tYSoauolyhenagA2sWno2TQ2WujI0HQd6s1Vw=="
},
"Microsoft.Data.Sqlite.Core": {
"type": "Transitive",
"resolved": "10.0.14",
@@ -10,6 +15,14 @@
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.ML.OnnxRuntime.Managed": {
"type": "Transitive",
"resolved": "1.31.1",
"contentHash": "158JCbNXN9/90LtjF4vHFiJYCF0bqF7CxLjm031jq7dJLEn/CtlHpMJm3UItQSIhQenlx+9Zuqi3zulwnsRVtA==",
"dependencies": {
"System.Numerics.Tensors": "9.0.0"
}
},
"SQLitePCLRaw.bundle_e_sqlite3": {
"type": "Transitive",
"resolved": "2.1.13",
@@ -37,10 +50,17 @@
"SQLitePCLRaw.core": "2.1.13"
}
},
"System.Numerics.Tensors": {
"type": "Transitive",
"resolved": "9.0.0",
"contentHash": "hyJB4UlpAi19Xr9AXzu2NuagKC4lPfHObNMEAA0HmqFz2rX7wKgzeYzO/jM/eBHDhnUGFFEjk5cOoJaxqg5J4A=="
},
"anubis": {
"type": "Project",
"dependencies": {
"Microsoft.Data.Sqlite": "[10.0.14, )",
"Microsoft.ML.OnnxRuntime": "[1.31.1, )",
"Microsoft.ML.Tokenizers": "[2.0.1, )",
"Npgsql": "[10.0.3, )",
"System.Security.Cryptography.ProtectedData": "[10.0.14, )"
}
@@ -56,6 +76,24 @@
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.ML.OnnxRuntime": {
"type": "CentralTransitive",
"requested": "[1.31.1, )",
"resolved": "1.31.1",
"contentHash": "XtsO/1JoKepkWbGk9/DcYtRUTduwJD68kw0eeaH5yy77YBivUZWhC1NBNlVecsBt9EitlQIjCd1hHDNXJ2jbQA==",
"dependencies": {
"Microsoft.ML.OnnxRuntime.Managed": "1.31.1"
}
},
"Microsoft.ML.Tokenizers": {
"type": "CentralTransitive",
"requested": "[2.0.1, )",
"resolved": "2.0.1",
"contentHash": "RZN3zslVWinBCMDAnbZWEY8lQbMkP54Yxm1s5NigPcrvYFzXMrDjNcVM9afq4SZHf1BV1rEmO0p7ZdfBLDbu4g==",
"dependencies": {
"Google.Protobuf": "3.30.2"
}
},
"Npgsql": {
"type": "CentralTransitive",
"requested": "[10.0.3, )",
@@ -68,6 +106,22 @@
"resolved": "10.0.14",
"contentHash": "UuaBUHgmtc9h6CMxaQqFDDJxkS5JVy7XEB+DbtCvD68GFcVM9/AccuNwFpARx8nwCnvjaxzoOBjG3gPz32P1Eg=="
}
},
"net10.0/win-x64": {
"SQLitePCLRaw.lib.e_sqlite3": {
"type": "Transitive",
"resolved": "2.1.13",
"contentHash": "D2UAuiGxFYBqeRXjjjGgvJ5UQifzn6wefmSqeKU7XcNGKLbJRP6X7kcPZ6opOBJGdCIlgbSxTvDpBbLvsN594A=="
},
"Microsoft.ML.OnnxRuntime": {
"type": "CentralTransitive",
"requested": "[1.31.1, )",
"resolved": "1.31.1",
"contentHash": "XtsO/1JoKepkWbGk9/DcYtRUTduwJD68kw0eeaH5yy77YBivUZWhC1NBNlVecsBt9EitlQIjCd1hHDNXJ2jbQA==",
"dependencies": {
"Microsoft.ML.OnnxRuntime.Managed": "1.31.1"
}
}
}
}
}
+38
View File
@@ -2,6 +2,11 @@
"version": 2,
"dependencies": {
"net10.0-windows7.0": {
"Google.Protobuf": {
"type": "Transitive",
"resolved": "3.30.2",
"contentHash": "Y2aOVLIt75yeeEWigg9V9YnjsEm53sADtLGq0gLhwaXpk3iu8tYSoauolyhenagA2sWno2TQ2WujI0HQd6s1Vw=="
},
"Microsoft.Data.Sqlite.Core": {
"type": "Transitive",
"resolved": "10.0.14",
@@ -23,6 +28,14 @@
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0"
}
},
"Microsoft.ML.OnnxRuntime.Managed": {
"type": "Transitive",
"resolved": "1.31.1",
"contentHash": "158JCbNXN9/90LtjF4vHFiJYCF0bqF7CxLjm031jq7dJLEn/CtlHpMJm3UItQSIhQenlx+9Zuqi3zulwnsRVtA==",
"dependencies": {
"System.Numerics.Tensors": "9.0.0"
}
},
"SQLitePCLRaw.bundle_e_sqlite3": {
"type": "Transitive",
"resolved": "2.1.13",
@@ -50,10 +63,17 @@
"SQLitePCLRaw.core": "2.1.13"
}
},
"System.Numerics.Tensors": {
"type": "Transitive",
"resolved": "9.0.0",
"contentHash": "hyJB4UlpAi19Xr9AXzu2NuagKC4lPfHObNMEAA0HmqFz2rX7wKgzeYzO/jM/eBHDhnUGFFEjk5cOoJaxqg5J4A=="
},
"anubis": {
"type": "Project",
"dependencies": {
"Microsoft.Data.Sqlite": "[10.0.14, )",
"Microsoft.ML.OnnxRuntime": "[1.31.1, )",
"Microsoft.ML.Tokenizers": "[2.0.1, )",
"Npgsql": "[10.0.3, )",
"System.Security.Cryptography.ProtectedData": "[10.0.14, )"
}
@@ -69,6 +89,24 @@
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.ML.OnnxRuntime": {
"type": "CentralTransitive",
"requested": "[1.31.1, )",
"resolved": "1.31.1",
"contentHash": "XtsO/1JoKepkWbGk9/DcYtRUTduwJD68kw0eeaH5yy77YBivUZWhC1NBNlVecsBt9EitlQIjCd1hHDNXJ2jbQA==",
"dependencies": {
"Microsoft.ML.OnnxRuntime.Managed": "1.31.1"
}
},
"Microsoft.ML.Tokenizers": {
"type": "CentralTransitive",
"requested": "[2.0.1, )",
"resolved": "2.0.1",
"contentHash": "RZN3zslVWinBCMDAnbZWEY8lQbMkP54Yxm1s5NigPcrvYFzXMrDjNcVM9afq4SZHf1BV1rEmO0p7ZdfBLDbu4g==",
"dependencies": {
"Google.Protobuf": "3.30.2"
}
},
"Npgsql": {
"type": "CentralTransitive",
"requested": "[10.0.3, )",
+7
View File
@@ -1,14 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<RootNamespace>Anubis</RootNamespace>
<!-- The Windows trial zip is published for win-x64 (tasks release-win). Declared here, the lock file also holds the
native packages of that runtime (ONNX Runtime), so publishing never changes it. -->
<RuntimeIdentifiers>win-x64</RuntimeIdentifiers>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Npgsql" />
<PackageReference Include="Microsoft.Data.Sqlite" />
<PackageReference Include="System.Security.Cryptography.ProtectedData" />
<PackageReference Include="Microsoft.ML.OnnxRuntime" />
<PackageReference Include="Microsoft.ML.Tokenizers" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Db\Migrations\*.sql" LogicalName="Anubis.Db.Migrations.%(Filename)%(Extension)" />
<!-- The tokenizer of the news classifier (ADR 0014); the ONNX model is downloaded at the first start. -->
<EmbeddedResource Include="News\Model\*.json;News\Model\*.txt" LogicalName="Anubis.News.Model.%(Filename)%(Extension)" />
<EmbeddedResource Include="Demo\Data\*" LogicalName="Anubis.Demo.Data.%(Filename)%(Extension)" />
<!-- The backtest outcomes travel with the code (SPEC 12.3): read at the first start. -->
<EmbeddedResource Include="..\..\docs\backtests\*.outcome.json" LogicalName="Anubis.Backtests.%(Filename)%(Extension)" />
+2 -1
View File
@@ -82,7 +82,7 @@ public sealed partial class MarketDataService : IDisposable
_universes = new UniverseStore(db, clock);
_builder = new UniverseBuilder(db, clock);
_states = new SourceStateStore(db, clock);
News = new News.NewsCollector(_http, db, clock, _logger);
News = new News.NewsCollector(_http, db, clock, _logger) { ModelFolder = data is null ? null : Path.Combine(data.Root, "models") };
}
public OkxClient Okx { get; }
@@ -153,6 +153,7 @@ public sealed partial class MarketDataService : IDisposable
public void Dispose()
{
_work.Dispose();
News.Dispose();
_http.Dispose();
}
+15
View File
@@ -0,0 +1,15 @@
# Tokenizer of the local news classifier
`vocab.json` and `merges.txt` are the byte-level BPE tokenizer of RoBERTa. They are used by the model
`mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis` (Apache-2.0), as exported to ONNX in
`Xenova/distilroberta-finetuned-financial-news-sentiment-analysis`.
- Revision: `e6953e30167c7fc3d1ad62f3df31617dd712fbc1`.
- Downloaded on 2026-11-15 with the user's permission (SPEC 4.5, ADR 0004, ADR 0014).
- SHA-256:
- `vocab.json`: `ed19656ea1707df69134c4af35c8ceda2cc9860bf2c3495026153a133670ab5e`
- `merges.txt`: `1ce1664773c50f3e0cc8842619a93edc4624525b728b188a9e0be33b7726adc5`
They travel inside the DLL. The ONNX model itself, `onnx/model_quantized.onnx` (82,763,251 bytes, SHA-256
`8fcf4873bf5e1679c77205ce621acecdd2cd8dd5baf18e930f10428008ed48ec`), is too large for the repository. The
application downloads it once into the `models` folder of the data directory and checks its hash (`ToneModel`).
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
{"<s>":0,"<pad>":1,"</s>":2,"<unk>":3,".":4,"Ġthe":5,",":6,"Ġto":7,"Ġand":8,"Ġof":9,"Ġa":10,"Ġin":11,"-":12,"Ġfor":13,"Ġthat":14,"Ġon":15,"Ġis":16,"âĢ":17,"'s":18,"Ġwith":19,"ĠThe":20,"Ġwas":21,"Ġ\"":22,"Ġat":23,"Ġit":24,"Ġas":25,"Ġsaid":26,"Ļ":27,"Ġbe":28,"s":29,"Ġby":30,"Ġfrom":31,"Ġare":32,"Ġhave":33,"Ġhas":34,":":35,"Ġ(":36,"Ġhe":37,"ĠI":38,"Ġhis":39,"Ġwill":40,"Ġan":41,"Ġthis":42,")":43,"ĠâĢ":44,"Ġnot":45,"Ŀ":46,"Ġyou":47,"ľ":48,"Ġtheir":49,"Ġor":50,"Ġthey":51,"Ġwe":52,"Ġbut":53,"Ġwho":54,"Ġmore":55,"Ġhad":56,"Ġbeen":57,"Ġwere":58,"Ġabout":59,",\"":60,"Ġwhich":61,"Ġup":62,"Ġits":63,"Ġcan":64,"Ġone":65,"Ġout":66,"Ġalso":67,"Ġ$":68,"Ġher":69,"Ġall":70,"Ġafter":71,".\"":72,"/":73,"Ġwould":74,"'t":75,"Ġyear":76,"Ġwhen":77,"Ġfirst":78,"Ġshe":79,"Ġtwo":80,"Ġover":81,"Ġpeople":82,"ĠA":83,"Ġour":84,"ĠIt":85,"Ġtime":86,"Ġthan":87,"Ġinto":88,"Ġthere":89,"t":90,"ĠHe":91,"Ġnew":92,"ĠâĢĶ":93,"Ġlast":94,"Ġjust":95,"ĠIn":96,"Ġother":97,"Ġso":98,"Ġwhat":99,"I":100,"Ġlike":101,"a":102,"Ġsome":103,"S":104,"ë":105,"Ġthem":106,"Ġyears":107,"'":108,"Ġdo":109,"Ġyour":110,"Ġ-":111,"Ġ1":112,"\"":113,"Ġif":114,"Ġcould":115,"?":116,"Ġno":117,"i":118,"m":119,"Ġget":120,"ĠU":121,"Ġnow":122,"Ġhim":123,"Ġback":124,"ĠBut":125,"ĠâĢĵ":126,"Ġmy":127,"Ġ'":128,"Ġonly":129,"Ġthree":130,";":131,"Ġ2":132,"The":133,"1":134,"Ġpercent":135,"Ġagainst":136,"Ġbefore":137,"Ġcompany":138,"o":139,"ĠTrump":140,"Ġhow":141,"Ġbecause":142,"Ġany":143,"Ġmost":144,"Ġbeing":145,"Ġmake":146,"Ġwhere":147,"Ġduring":148,"Ġthrough":149,"Ġwhile":150,"000":151,"ĠThis":152,"Ġmillion":153,"ing":154,"Ġ3":155,"Ġmade":156,"Ġwell":157,"Ġ10":158,"Ġdown":159,"Ġoff":160,"Ġsays":161,"Ġme":162,"ĠB":163,"Ġgoing":164,"Ġteam":165,"ĠWe":166,"Ġthose":167,"Ġgovernment":168,"Ġway":169,"We":170,"Ġmany":171,"Ġthen":172,"Ġwork":173,"Ġtold":174,"com":175,"2":176,"Ġgame":177,"ĠAnd":178,"in":179,"year":180,"Ġp":181,"Ġvery":182,"Ġday":183,"Ġhome":184,"Ġtake":185,"Ġweek":186,"Ġsince":187,"ĠNew":188,"Ġmay":189,"Ġeven":190,"Ġseason":191,"Ġsee":192,"Ġ2017":193,"Ġstate":194,"Ġ5":195,"ed":196,"Ġshould":197,"Ġaround":198,"Ġ2018":199,"Ġsecond":200,"Ġus":201,"Ġstill":202,"Ġmuch":203,"Ġ4":204,"Ġgood":205,"Ġthink":206,"%":207,"ĠS":208,"Ġthese":209,"Ġmarket":210,"ĠD":211,"th":212,"Ġgo":213,"'re":214,"Ġsuch":215,"Ġknow":216,"Ġincluding":217,"Ġdon":218,"y":219,"Ġnext":220,"ĠP":221,"Ġdid":222,"Ġunder":223,"Ġsay":224,"en":225,"ĠL":226,"Ġbetween":227,"Ġper":228,"ĠK":229,"ĠC":230,"Ġ6":231,"Ġworld":232,"Ġpart":233,"ĠN":234,"Ġright":235,"Ġwant":236,"Ġfour":237,"),":238,"Ġhigh":239,"Ġneed":240,"re":241,"e":242,"It":243,"Ġhelp":244,"5":245,"3":246,"Ġcountry":247,"ĠR":248,"Ġpolice":249,"A":250,"Ġlong":251,"ĠThey":252,"Ġend":253,"er":254,"ĠT":255,"ĠM":256,"u":257,"Ġboth":258,"Ġhere":259,"an":260,"on":261,"Ġ7":262,"Ġde":263,"ĠShe":264,"Ġbusiness":265,"Ġreport":266,"j":267,"ers":268,"Ġreally":269,"ĠPresident":270,"ar":271,"ĠG":272,"ĠFriday":273,"ĠF":274,"Ġbest":275,"Ġsame":276,"Ġanother":277,"Ġset":278,"old":279,"ĠThat":280,"as":281,"n":282,"Ġcome":283,"Ġfamily":284,"Ġpublic":285,"ĠFor":286,"ĠAs":287,"0":288,"ĠH":289,"Ġ8":290,"Ġ20":291,"Ġfive":292,"es":293,"ĠTuesday":294,"Ġn":295,"ĠThursday":296,"Ġquarter":297,"h":298,"Ġtop":299,"Ġgot":300,"Ġlife":301,"ĠMonday":302,"Ġfound":303,"Ġuse":304,"ĠW":305,"4":306,"ĠWednesday":307,"Ġown":308,"Ġaccording":309,"Ġplay":310,"Ġshow":311,"ĠSt":312,"Ġman":313,"Ġleft":314,"ĠUnited":315,"Ġ12":316,"Ġplace":317,"ĠIf":318,"Ġlot":319,"Ġformer":320,"Ġ0":321,").":322,"Ġsupport":323,"ie":324,"Ġbillion":325,"Ġt":326,"Ġshares":327,"!":328,"z":329,"k":330,"ĠState":331,"Ġpoints":332,"Ġgroup":333,"Ġschool":334,"Ġinformation":335,"Ġ2016":336,"al":337,"r":338,"Ġwin":339,"Ġnews":340,"Ġused":341,"Ġput":342,"Ġcity":343,"ĠJ":344,"ĠThere":345,"Ġnumber":346,"C":347,"'ve":348,"Ġeach":349,"Ġtoo":350,"Ġwon":351,"ly":352,"Ġmonth":353,"is":354,"Ġadded":355,"Ġlook":356,"Ġbetter":357,"Ġevery":358,"Ġ&":359,"Ġdays":360,"Ġ9":361,"Ġtook":362,"Ġnight":363,"Ġe":364,"Ġ11":365,"os":366,"Ġfew":367,"or":368,"ĠNorth":369,"ĠYou":370,"Ġthird":371,"Ġgreat":372,"Ġcalled":373,"ĠOn":374,"Ġpast":375,"Ġcame":376,"Ġmonths":377,"ĠSaturday":378,"Ġ15":379,"Ġbig":380,"ĠE":381,"ĠUS":382,"Ġthings":383,"ĠO":384,"Ġd":385,"Ġstart":386,"B":387,"Ġstock":388,"Ġ30":389,"Ġwomen":390,"ĠSouth":391,"ĠMay":392,"Ġnever":393,"Ġpresident":394,"ĠSunday":395,"Ġwithout":396,"man":397,"8":398,"Ġdidn":399,"Ġlocal":400,"6":401,"Ġsomething":402,"Ġcase":403,"ĠAll":404,"it":405,"7":406,"ĠSo":407,"Ġchildren":408,"Ġaway":409,"Ġlittle":410,"Ġsix":411,"ĠCity":412,"ĠCounty":413,"Ġdata":414,"at":415,"Ġalready":416,"d":417,"Ġmoney":418,"Ġearly":419,"Ġacross":420,"Ġexpected":421,"Ġrun":422,"Ġlater":423,"am":424,"ĠpricLine truncated
+65 -3
View File
@@ -5,6 +5,7 @@ using Anubis.Data;
using Anubis.Db;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.ML.OnnxRuntime;
namespace Anubis.News;
@@ -13,7 +14,7 @@ namespace Anubis.News;
/// conditional on what the source said the last time (ETag, Last-Modified), and spaced out more and more for a source
/// that keeps failing. The text it reads is untrusted data: it is parsed, never followed.
/// </summary>
public sealed partial class NewsCollector(HttpClient http, Database db, IClock clock, ILogger? logger = null)
public sealed partial class NewsCollector(HttpClient http, Database db, IClock clock, ILogger? logger = null) : IDisposable
{
public const string JobName = "notizie";
@@ -35,14 +36,69 @@ public sealed partial class NewsCollector(HttpClient http, Database db, IClock c
public NewsStore Store => _store;
/// <summary>The local classifier of SPEC 4.5; without it the tone is unknown and only the keywords judge.</summary>
public IToneClassifier? Classifier { get; init; }
/// <summary>A model that could not be downloaded or opened is tried again after this long.</summary>
public static readonly TimeSpan ModelRetry = TimeSpan.FromHours(6);
private readonly CancellationTokenSource _stopping = new();
private IToneClassifier? _classifier;
private Task? _loading;
private DateTimeOffset _nextModelTry = DateTimeOffset.MinValue;
/// <summary>
/// The local classifier of SPEC 4.5. Without it the tone is unknown and only the keywords judge: the news keep
/// coming while the model downloads, and the articles read meanwhile simply have no score.
/// </summary>
public IToneClassifier? Classifier
{
get => Volatile.Read(ref _classifier);
init => _classifier = value;
}
/// <summary>Where the model is kept (the <c>models</c> folder of the data directory); null: no model, as in the tests.</summary>
public string? ModelFolder { get; init; }
public void Dispose()
{
_stopping.Cancel();
_stopping.Dispose();
(Volatile.Read(ref _classifier) as IDisposable)?.Dispose();
}
/// <summary>Starts, in the background, the download and the opening of the model, once and then every 6 hours if it fails.</summary>
private void StartModel()
{
if (Classifier is not null || ModelFolder is not { } folder || _loading is { IsCompleted: false } || clock.UtcNow < _nextModelTry)
{
return;
}
_nextModelTry = clock.UtcNow + ModelRetry;
var stopping = _stopping.Token;
_loading = Task.Run(async () =>
{
try
{
var path = await ToneModel.EnsureAsync(http, folder, stopping).ConfigureAwait(false);
Volatile.Write(ref _classifier, new OnnxToneClassifier(path));
LogModelReady(_logger, ToneModel.Revision[..8]);
}
catch (OperationCanceledException) when (stopping.IsCancellationRequested)
{
}
catch (Exception e) when (e is HttpRequestException or IOException or InvalidDataException or OperationCanceledException or OnnxRuntimeException
or UnauthorizedAccessException)
{
LogModelFailed(_logger, e.Message);
}
}, CancellationToken.None);
}
public ScheduledJob Job() => new(JobName, "Lettura delle notizie", Schedule.Every(Interval), RunOnceAsync) { MaxLateness = Interval };
/// <summary>One round over the sources that are due.</summary>
public async Task RunOnceAsync(CancellationToken cancellationToken)
{
StartModel();
await _store.EnsureDefaultsAsync(cancellationToken).ConfigureAwait(false);
var dictionary = await DictionaryAsync(cancellationToken).ConfigureAwait(false);
var first = true;
@@ -167,4 +223,10 @@ public sealed partial class NewsCollector(HttpClient http, Database db, IClock c
[LoggerMessage(Level = LogLevel.Warning, Message = "News source {Source} failed: {Error}")]
private static partial void LogFailed(ILogger logger, string source, string error);
[LoggerMessage(Level = LogLevel.Information, Message = "News classifier ready (model revision {Revision})")]
private static partial void LogModelReady(ILogger logger, string revision);
[LoggerMessage(Level = LogLevel.Warning, Message = "News classifier not available, keywords only until the next try: {Error}")]
private static partial void LogModelFailed(ILogger logger, string error);
}
+199
View File
@@ -0,0 +1,199 @@
using System.Security.Cryptography;
using System.Text.Json;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.Tokenizers;
namespace Anubis.News;
/// <summary>
/// The model of SPEC 4.5: <c>mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis</c> (Apache-2.0) in its
/// ONNX export by Xenova, at a fixed revision and with its hash checked (ADR 0004, ADR 0014). The tokenizer travels in
/// the DLL; the model, 83 MB, is downloaded once into the <c>models</c> folder of the data directory.
/// </summary>
public static class ToneModel
{
public const string Repository = "Xenova/distilroberta-finetuned-financial-news-sentiment-analysis";
public const string Revision = "e6953e30167c7fc3d1ad62f3df31617dd712fbc1";
public const string RemotePath = "onnx/model_quantized.onnx";
public const string FileName = "distilroberta-financial-news-sentiment-e6953e30-quantized.onnx";
public const long Size = 82_763_251;
public const string Sha256 = "8fcf4873bf5e1679c77205ce621acecdd2cd8dd5baf18e930f10428008ed48ec";
public static readonly Uri Url = new($"https://huggingface.co/{Repository}/resolve/{Revision}/{RemotePath}");
/// <summary>The longest download allowed: slow connections get there, a stuck one does not hold the job forever.</summary>
public static readonly TimeSpan DownloadTimeout = TimeSpan.FromMinutes(30);
/// <summary>
/// The path of the model in <paramref name="folder"/>, downloaded and checked if it is not there yet. A file of the
/// wrong size or hash is never used: it is replaced. Throws when the download fails or does not match.
/// </summary>
public static async Task<string> EnsureAsync(HttpClient http, string folder, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(http);
Directory.CreateDirectory(folder);
var path = Path.Combine(folder, FileName);
if (File.Exists(path) && new FileInfo(path).Length == Size && await HashAsync(path, cancellationToken).ConfigureAwait(false) == Sha256)
{
return path;
}
var part = path + ".part";
using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
{
timeout.CancelAfter(DownloadTimeout);
using var response = await http.GetAsync(Url, HttpCompletionOption.ResponseHeadersRead, timeout.Token).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var target = new FileStream(part, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16, useAsync: true);
await using (target.ConfigureAwait(false))
{
var source = await response.Content.ReadAsStreamAsync(timeout.Token).ConfigureAwait(false);
await using (source.ConfigureAwait(false))
{
var buffer = new byte[1 << 16];
long total = 0;
int read;
while ((read = await source.ReadAsync(buffer, timeout.Token).ConfigureAwait(false)) > 0)
{
total += read;
if (total > Size)
{
throw new InvalidDataException($"The model is larger than the {Size} bytes expected.");
}
await target.WriteAsync(buffer.AsMemory(0, read), timeout.Token).ConfigureAwait(false);
}
}
}
}
var hash = await HashAsync(part, cancellationToken).ConfigureAwait(false);
if (new FileInfo(part).Length != Size || hash != Sha256)
{
File.Delete(part);
throw new InvalidDataException($"The downloaded model does not match: SHA-256 {hash}, expected {Sha256}.");
}
File.Move(part, path, overwrite: true);
return path;
}
private static async Task<string> HashAsync(string path, CancellationToken cancellationToken)
{
var file = File.OpenRead(path);
await using (file.ConfigureAwait(false))
{
return Convert.ToHexStringLower(await SHA256.HashDataAsync(file, cancellationToken).ConfigureAwait(false));
}
}
}
/// <summary>
/// The local classifier of SPEC 4.5 on ONNX Runtime. The tokenizer is RoBERTa's byte-level BPE, the one of GPT-2 with
/// <c>&lt;s&gt;</c> and <c>&lt;/s&gt;</c> around the text; the test compares its ids with the original. One thread, so the
/// classifier never takes the processor away from the trading engine; 10–20 ms per title.
/// </summary>
public sealed class OnnxToneClassifier : IToneClassifier, IDisposable
{
/// <summary>Titles are short: 128 tokens hold any of them, and the model's limit is 512.</summary>
public const int MaxTokens = 128;
private const int Start = 0;
private const int End = 2;
// Classes of the model (config.json): 0 negative, 1 neutral, 2 positive.
private const int NegativeClass = 0;
private const int NeutralClass = 1;
private const int PositiveClass = 2;
private static readonly Lazy<BpeTokenizer> Tokenizer = new(LoadTokenizer);
private readonly InferenceSession _session;
private readonly string[] _inputs;
private readonly string[] _output;
public OnnxToneClassifier(string modelPath)
{
using var options = new SessionOptions
{
IntraOpNumThreads = 1,
InterOpNumThreads = 1,
GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,
};
_session = new InferenceSession(modelPath, options);
_inputs = [.. _session.InputMetadata.Keys];
_output = [_session.OutputMetadata.Keys.First()];
if (!_inputs.Contains("input_ids"))
{
_session.Dispose();
throw new InvalidDataException("The model has no input_ids input.");
}
}
/// <summary>The token ids the model reads, as the original RoBERTa tokenizer gives them.</summary>
public static IReadOnlyList<int> Ids(string text)
{
ArgumentNullException.ThrowIfNull(text);
var body = Tokenizer.Value.EncodeToIds(text);
var ids = new List<int>(Math.Min(body.Count, MaxTokens - 2) + 2) { Start };
ids.AddRange(body.Take(MaxTokens - 2));
ids.Add(End);
return ids;
}
public ToneScore Classify(string text)
{
var ids = Ids(text);
var shape = new long[] { 1, ids.Count };
var values = new List<OrtValue>(_inputs.Length);
try
{
foreach (var name in _inputs)
{
var data = name switch
{
"input_ids" => ids.Select(i => (long)i).ToArray(),
"attention_mask" => Enumerable.Repeat(1L, ids.Count).ToArray(),
_ => new long[ids.Count],
};
values.Add(OrtValue.CreateTensorValueFromMemory(data, shape));
}
using var run = new RunOptions();
using var outputs = _session.Run(run, _inputs, values, _output);
var logits = outputs[0].GetTensorDataAsSpan<float>();
var max = Math.Max(logits[NegativeClass], Math.Max(logits[NeutralClass], logits[PositiveClass]));
double negative = Math.Exp(logits[NegativeClass] - max), neutral = Math.Exp(logits[NeutralClass] - max), positive = Math.Exp(logits[PositiveClass] - max);
var sum = negative + neutral + positive;
return new ToneScore(positive / sum, negative / sum, neutral / sum);
}
finally
{
foreach (var value in values)
{
value.Dispose();
}
}
}
public void Dispose() => _session.Dispose();
private static BpeTokenizer LoadTokenizer()
{
var assembly = typeof(OnnxToneClassifier).Assembly;
using var vocab = assembly.GetManifestResourceStream("Anubis.News.Model.vocab.json") ?? throw new InvalidOperationException("vocab.json is missing.");
using var merges = assembly.GetManifestResourceStream("Anubis.News.Model.merges.txt") ?? throw new InvalidOperationException("merges.txt is missing.");
var vocabulary = JsonSerializer.Deserialize<Dictionary<string, int>>(vocab) ?? throw new InvalidDataException("vocab.json is empty.");
using var reader = new StreamReader(merges);
var pairs = reader.ReadToEnd().Split('\n').Where(l => l.Length > 0 && !l.StartsWith("#version", StringComparison.Ordinal)).ToList();
// Not CodeGenTokenizer.Create: it adds CodeGen's own tokens for runs of spaces, ids RoBERTa does not have. No special
// tokens either: a headline that contains "<s>" or "<mask>" is read as text, never as a mark for the model.
return BpeTokenizer.Create(new BpeOptions(vocabulary)
{
Merges = pairs,
PreTokenizer = RobertaPreTokenizer.Instance,
ByteLevel = true,
});
}
}
+52
View File
@@ -13,6 +13,24 @@
"SQLitePCLRaw.core": "2.1.13"
}
},
"Microsoft.ML.OnnxRuntime": {
"type": "Direct",
"requested": "[1.31.1, )",
"resolved": "1.31.1",
"contentHash": "XtsO/1JoKepkWbGk9/DcYtRUTduwJD68kw0eeaH5yy77YBivUZWhC1NBNlVecsBt9EitlQIjCd1hHDNXJ2jbQA==",
"dependencies": {
"Microsoft.ML.OnnxRuntime.Managed": "1.31.1"
}
},
"Microsoft.ML.Tokenizers": {
"type": "Direct",
"requested": "[2.0.1, )",
"resolved": "2.0.1",
"contentHash": "RZN3zslVWinBCMDAnbZWEY8lQbMkP54Yxm1s5NigPcrvYFzXMrDjNcVM9afq4SZHf1BV1rEmO0p7ZdfBLDbu4g==",
"dependencies": {
"Google.Protobuf": "3.30.2"
}
},
"Npgsql": {
"type": "Direct",
"requested": "[10.0.3, )",
@@ -28,6 +46,11 @@
"resolved": "10.0.14",
"contentHash": "UuaBUHgmtc9h6CMxaQqFDDJxkS5JVy7XEB+DbtCvD68GFcVM9/AccuNwFpARx8nwCnvjaxzoOBjG3gPz32P1Eg=="
},
"Google.Protobuf": {
"type": "Transitive",
"resolved": "3.30.2",
"contentHash": "Y2aOVLIt75yeeEWigg9V9YnjsEm53sADtLGq0gLhwaXpk3iu8tYSoauolyhenagA2sWno2TQ2WujI0HQd6s1Vw=="
},
"Microsoft.Data.Sqlite.Core": {
"type": "Transitive",
"resolved": "10.0.14",
@@ -49,6 +72,14 @@
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0"
}
},
"Microsoft.ML.OnnxRuntime.Managed": {
"type": "Transitive",
"resolved": "1.31.1",
"contentHash": "158JCbNXN9/90LtjF4vHFiJYCF0bqF7CxLjm031jq7dJLEn/CtlHpMJm3UItQSIhQenlx+9Zuqi3zulwnsRVtA==",
"dependencies": {
"System.Numerics.Tensors": "9.0.0"
}
},
"SQLitePCLRaw.bundle_e_sqlite3": {
"type": "Transitive",
"resolved": "2.1.13",
@@ -75,6 +106,27 @@
"dependencies": {
"SQLitePCLRaw.core": "2.1.13"
}
},
"System.Numerics.Tensors": {
"type": "Transitive",
"resolved": "9.0.0",
"contentHash": "hyJB4UlpAi19Xr9AXzu2NuagKC4lPfHObNMEAA0HmqFz2rX7wKgzeYzO/jM/eBHDhnUGFFEjk5cOoJaxqg5J4A=="
}
},
"net10.0/win-x64": {
"Microsoft.ML.OnnxRuntime": {
"type": "Direct",
"requested": "[1.31.1, )",
"resolved": "1.31.1",
"contentHash": "XtsO/1JoKepkWbGk9/DcYtRUTduwJD68kw0eeaH5yy77YBivUZWhC1NBNlVecsBt9EitlQIjCd1hHDNXJ2jbQA==",
"dependencies": {
"Microsoft.ML.OnnxRuntime.Managed": "1.31.1"
}
},
"SQLitePCLRaw.lib.e_sqlite3": {
"type": "Transitive",
"resolved": "2.1.13",
"contentHash": "D2UAuiGxFYBqeRXjjjGgvJ5UQifzn6wefmSqeKU7XcNGKLbJRP6X7kcPZ6opOBJGdCIlgbSxTvDpBbLvsN594A=="
}
}
}