-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
220 lines (189 loc) · 8.75 KB
/
Copy pathProgram.cs
File metadata and controls
220 lines (189 loc) · 8.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using Newtonsoft.Json;
namespace OnnxInference
{
class Program
{
// Define paths to your ONNX models and vocab files
private static readonly string VocabPath = "vocabs.json";
private static readonly string EncoderModelPath = "encoder.onnx";
private static readonly string DecoderModelPath = "decoder.onnx";
private static Dictionary<char, long> letter2id;
private static Dictionary<string, long> ph2id;
private static Dictionary<long, string> id2ph;
static void Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Usage: OnnxInference.exe <input_file> <output_file>");
return;
}
string inputFile = args[0];
string outputFile = args[1];
if (!File.Exists(inputFile))
{
Console.WriteLine("Invalid input file.");
return;
}
Console.WriteLine("Loading vocabularies...");
LoadVocabularies(VocabPath);
Console.WriteLine("Vocabularies loaded.");
Console.WriteLine("Initializing ONNX sessions...");
using (var encSession = new InferenceSession(EncoderModelPath))
using (var decSession = new InferenceSession(DecoderModelPath))
{
Console.WriteLine("ONNX sessions initialized.");
Console.WriteLine($"Processing words from {inputFile}...");
ProcessFile(inputFile, outputFile, encSession, decSession);
Console.WriteLine($"Finished. Output saved to {outputFile}");
}
}
private static void ProcessFile(string inputFile, string outputFile, InferenceSession encSession, InferenceSession decSession)
{
try
{
var lines = File.ReadLines(inputFile, Encoding.UTF8);
using (var writer = new StreamWriter(outputFile, false, Encoding.UTF8))
{
foreach (var line in lines)
{
string word = line.Trim();
if (string.IsNullOrEmpty(word))
continue;
string normalizedWord = Regex.Replace(word, @"\+(.)", "$1+");
string phonemes = InferWord(normalizedWord, encSession, decSession, maxLen: 50, beamSize: 5);
writer.WriteLine($"{word}\t{phonemes}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
private class Beam
{
public double LogProb;
public List<int> Tokens;
public Tensor<float> Hidden;
public Tensor<float> Cell;
}
private static string InferWord(string word, InferenceSession encSession, InferenceSession decSession, int maxLen = 50, int beamSize = 5)
{
// Encode input word
var wordIds = word.Select(c => letter2id.ContainsKey(c) ? letter2id[c] : 0).ToList();
var srcInput = new DenseTensor<long>(wordIds.ToArray(), new[] { 1, wordIds.Count });
var srcLenInput = new DenseTensor<long>(new long[] { wordIds.Count }, new[] { 1 });
var encInputs = new List<NamedOnnxValue>
{
NamedOnnxValue.CreateFromTensor("src_input", srcInput),
NamedOnnxValue.CreateFromTensor("src_len_input", srcLenInput)
};
var encOutputs = encSession.Run(encInputs);
var encoderHidden = encOutputs.First(v => v.Name == "encoder_hidden").AsTensor<float>();
var encoderCell = encOutputs.First(v => v.Name == "encoder_cell").AsTensor<float>();
int sosId = (int)(ph2id.ContainsKey("<sos>") ? ph2id["<sos>"] : 1);
int eosId = (int)(ph2id.ContainsKey("<eos>") ? ph2id["<eos>"] : ph2id.Values.Max());
// Initialize beams with <sos>
var beams = new List<Beam>
{
new Beam { LogProb = 0.0, Tokens = new List<int> { sosId }, Hidden = encoderHidden, Cell = encoderCell }
};
var completed = new List<Beam>();
for (int step = 0; step < maxLen; step++)
{
var allCandidates = new List<Beam>();
foreach (var beam in beams)
{
int lastToken = beam.Tokens.Last();
if (lastToken == eosId)
{
completed.Add(beam);
continue;
}
var decInputTensor = new DenseTensor<long>(new long[] { lastToken }, new[] { 1 });
var decInputs = new List<NamedOnnxValue>
{
NamedOnnxValue.CreateFromTensor("input_token", decInputTensor),
NamedOnnxValue.CreateFromTensor("decoder_hidden_in", beam.Hidden),
NamedOnnxValue.CreateFromTensor("decoder_cell_in", beam.Cell)
};
var decOutputs = decSession.Run(decInputs);
var outputLogits = decOutputs.First(v => v.Name == "output_logits").AsTensor<float>().ToArray();
// Convert logits -> log probabilities
double maxLogit = outputLogits.Max();
var exp = outputLogits.Select(x => Math.Exp(x - maxLogit)).ToArray();
double sumExp = exp.Sum();
var logProbs = exp.Select(x => Math.Log(x / sumExp)).ToArray();
// Take top-k
var topk = logProbs
.Select((lp, idx) => new { Idx = idx, LogP = lp })
.OrderByDescending(x => x.LogP)
.Take(beamSize);
foreach (var candidate in topk)
{
var newHidden = decOutputs.First(v => v.Name == "decoder_hidden_out").AsTensor<float>();
var newCell = decOutputs.First(v => v.Name == "decoder_cell_out").AsTensor<float>();
allCandidates.Add(new Beam
{
LogProb = beam.LogProb + candidate.LogP,
Tokens = beam.Tokens.Concat(new[] { candidate.Idx }).ToList(),
Hidden = newHidden,
Cell = newCell
});
}
}
if (!allCandidates.Any()) break;
beams = allCandidates.OrderByDescending(b => b.LogProb).Take(beamSize).ToList();
if (beams.All(b => b.Tokens.Last() == eosId))
{
completed.AddRange(beams);
break;
}
}
var best = completed.Any()
? completed.OrderByDescending(b => b.LogProb).First()
: beams.First();
// Convert token ids -> phoneme string
var sb = new StringBuilder();
foreach (var token in best.Tokens.Skip(1)) // skip sos
{
if (token == eosId) break;
if (id2ph.TryGetValue(token, out var ph))
sb.Append(ph);
}
return sb.ToString();
}
private static void LoadVocabularies(string path)
{
try
{
var jsonText = File.ReadAllText(path, Encoding.UTF8);
var vocabData = JsonConvert.DeserializeObject<VocabData>(jsonText);
letter2id = vocabData.letter2id
.Where(kvp => kvp.Key.Length == 1)
.ToDictionary(kvp => kvp.Key[0], kvp => kvp.Value);
ph2id = vocabData.ph2id;
id2ph = vocabData.id2ph.ToDictionary(kvp => long.Parse(kvp.Key), kvp => kvp.Value);
}
catch (Exception ex)
{
Console.WriteLine($"Failed to load vocabularies: {ex.Message}");
throw;
}
}
}
public class VocabData
{
public Dictionary<string, long> letter2id { get; set; }
public Dictionary<string, long> ph2id { get; set; }
public Dictionary<string, string> id2ph { get; set; }
}
}