krishnah27 commited on
Commit
1b84bf9
·
verified ·
1 Parent(s): bd0bac4

Upload run_onnx_inference.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. run_onnx_inference.py +70 -0
run_onnx_inference.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import onnxruntime as ort
3
+ import torch
4
+ import torch.nn.functional as F
5
+ from pathlib import Path
6
+
7
+ from src.s02_tokenizer import MusicTokenizer, BOS_TOKEN, EOS_TOKEN
8
+ from src.s06_generator import top_k_top_p_filter, apply_repetition_penalty
9
+
10
+ def generate_with_onnx(onnx_path: str, max_tokens: int = 256, temp: float = 0.85) -> list[int]:
11
+ """Generates music tokens using the exported ONNX model."""
12
+
13
+ # 1. Load ONNX model session
14
+ # Selects CUDA (GPU) if available, falls back to CPU
15
+ providers = ['CUDAExecutionProvider', 'CPUExecutionProvider']
16
+ print(f"Loading ONNX session from {onnx_path}...")
17
+ session = ort.InferenceSession(onnx_path, providers=providers)
18
+ print(f"Active Execution Providers: {session.get_providers()}")
19
+
20
+ # 2. Setup prompt (starts with Beginning of Sequence token)
21
+ generated = [BOS_TOKEN]
22
+
23
+ # 3. Autoregressive loop
24
+ print(f"Generating up to {max_tokens} tokens...")
25
+ for step in range(max_tokens - len(generated)):
26
+ # Format input data: must be int64 numpy array of shape (batch_size, sequence_length)
27
+ input_data = np.array([generated], dtype=np.int64)
28
+
29
+ # Run model inference
30
+ # input_ids -> output name "logits"
31
+ outputs = session.run(["logits"], {"input_ids": input_data})
32
+
33
+ # Get logits for the last token position
34
+ logits = outputs[0][0, -1, :] # shape: (vocab_size,)
35
+ logits_tensor = torch.tensor(logits).unsqueeze(0) / max(temp, 1e-8)
36
+
37
+ # Apply sampling filters
38
+ logits_tensor = apply_repetition_penalty(logits_tensor, generated, penalty=1.15)
39
+ logits_tensor = top_k_top_p_filter(logits_tensor, top_k=40, top_p=0.92)
40
+
41
+ # Sample next token
42
+ probs = F.softmax(logits_tensor, dim=-1)
43
+ next_token = torch.multinomial(probs, num_samples=1).item()
44
+
45
+ generated.append(next_token)
46
+
47
+ if next_token == EOS_TOKEN:
48
+ break
49
+
50
+ return generated
51
+
52
+ def main():
53
+ onnx_path = "checkpoints/model.onnx"
54
+ output_path = "output/onnx_generated.mid"
55
+
56
+ # Generate tokens
57
+ tokens = generate_with_onnx(onnx_path, max_tokens=512, temp=0.85)
58
+ print(f"Generated {len(tokens)} tokens.")
59
+
60
+ # Decode back to MIDI file
61
+ tokenizer = MusicTokenizer()
62
+ midi = tokenizer.tokens_to_midi(tokens)
63
+
64
+ # Save output
65
+ Path(output_path).parent.mkdir(parents=True, exist_ok=True)
66
+ midi.write(output_path)
67
+ print(f"Saved ONNX generated MIDI to: {output_path}")
68
+
69
+ if __name__ == "__main__":
70
+ main()