sankalphs commited on
Commit
ef72e30
·
1 Parent(s): 2c4122b

fix: add .gitattributes for binary files, Dockerfile --chown for weights

Browse files
Dockerfile CHANGED
@@ -5,9 +5,14 @@ WORKDIR /app
5
  COPY requirements.txt .
6
  RUN pip install --no-cache-dir -r requirements.txt
7
 
 
8
  COPY app.py .
9
  COPY tiny_fighter.py .
10
- COPY tiny_fighter.pt .
 
 
 
 
11
  COPY static/ static/
12
 
13
  ENV PORT=7860
 
5
  COPY requirements.txt .
6
  RUN pip install --no-cache-dir -r requirements.txt
7
 
8
+ # Copy text files first
9
  COPY app.py .
10
  COPY tiny_fighter.py .
11
+
12
+ # Copy binary weights file - use --chown to avoid permission issues
13
+ COPY --chown=root:root tiny_fighter.pt .
14
+
15
+ # Copy static assets
16
  COPY static/ static/
17
 
18
  ENV PORT=7860
app.py CHANGED
@@ -32,7 +32,11 @@ def get_model() -> TinyFighter:
32
  if _tiny_model is None:
33
  _tiny_model = TinyFighter()
34
  if WEIGHTS_PATH.exists():
35
- _tiny_model.load_state_dict(torch.load(WEIGHTS_PATH, map_location="cpu"))
 
 
 
 
36
  _tiny_model.eval()
37
  return _tiny_model
38
 
 
32
  if _tiny_model is None:
33
  _tiny_model = TinyFighter()
34
  if WEIGHTS_PATH.exists():
35
+ # Debug: verify file integrity
36
+ with open(WEIGHTS_PATH, "rb") as f:
37
+ head = f.read(8)
38
+ print(f"Loading weights from {WEIGHTS_PATH}, size={WEIGHTS_PATH.stat().st_size}, head={head[:4].hex()}")
39
+ _tiny_model.load_state_dict(torch.load(WEIGHTS_PATH, map_location="cpu", weights_only=False))
40
  _tiny_model.eval()
41
  return _tiny_model
42
 
docs/DEMO_VIDEO_SCRIPT.md ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Duel of Nemotron — Demo Video Script
2
+
3
+ *Target length: 60–90 seconds. Vertical or landscape.*
4
+
5
+ ## Beat 1 (0:00–0:05) — Cold open
6
+ *[Screen: black with text fade-in]*
7
+ **"What if a 4-billion parameter model and a 142-thousand parameter model fought together?"**
8
+
9
+ ## Beat 2 (0:05–0:20) — The game
10
+ *[Screen: Space loads, character select, then the arena]*
11
+ - Pick a fighter (ronin vs brute)
12
+ - First few seconds of combat — show the NPC reacting to your moves
13
+ - HUD shows the Nemotron "reasoning" text in real time
14
+ - Text overlay: *"Tiny model on CPU picks each move. Nemotron on Modal sets the strategy."*
15
+
16
+ ## Beat 3 (0:20–0:40) — The strategy switch
17
+ *[Screen: gameplay continues, then the Nemotron output changes]*
18
+ - Player lands a few hits, NPC's HP drops
19
+ - Nemotron reasoning updates: *"NPC adapts: high aggression, parry-focused"*
20
+ - NPC starts parrying and countering
21
+ - Text overlay: *"Every ~10 moves, Nemotron on Modal A10 picks a new mode"*
22
+ - Show the `/strategize` response JSON in a small overlay (fades in for 2s)
23
+
24
+ ## Beat 4 (0:40–0:55) — The tiny model in action
25
+ *[Screen: cut to the Gradio panel at /gradio]*
26
+ - Show the Tiny Fighter Gradio demo
27
+ - Move the sliders: aggression 0.9, defense 0.1, kick_affinity 0.8
28
+ - Click "Pick Move" → model outputs "kick" with 0.25 confidence
29
+ - Text overlay: *"142k params. 0.093ms inference. Runs on CPU in the Space."*
30
+
31
+ ## Beat 5 (0:55–1:05) — Outro
32
+ *[Screen: split view — the 3D game on the left, the Gradio demo on the right]*
33
+ **"Nemotron 3 Nano 4B, fine-tuned via AlphaGo-style self-play. The tiny model learned to execute the strategy in 20 minutes on a laptop."**
34
+ - HF Space link
35
+ - Hackathon credits
36
+
37
+ ## Recording tips
38
+ - Record at 1080p, 30fps
39
+ - Use OBS for screen capture
40
+ - Pre-warm Nemotron before recording (60–90s cold start)
41
+ - Add subtle lo-fi music (royalty-free)
42
+ - The Tiny Fighter inference is sub-millisecond, so it's instant
43
+
44
+ ## Post-production
45
+ - Add captions for accessibility
46
+ - Export as MP4, H.264
47
+ - Upload to YouTube (unlisted) or Twitter
48
+ - Submit link with the Space URL
docs/FIELD_NOTES.md ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Duel of Nemotron — Field Notes
2
+
3
+ *Built for the [Build Small Hackathon](https://huggingface.co/build-small-hackathon) by [@sankalphs](https://huggingface.co/sankalphs)*
4
+
5
+ ## What I built
6
+
7
+ A 3D fighting game where the NPC opponent is powered by **two models** working together:
8
+
9
+ - **Nemotron 3 Nano 4B** (fine-tuned, runs on Modal A10) — the *strategist*. Every several moves it looks at the fight state and outputs a mode: aggressive, defensive, grappling, etc.
10
+ - **Tiny Fighter** (~142k parameters, runs on CPU in the HF Space) — the *executor*. Conditioned on Nemotron's strategic weights, it picks the actual next move in **less than 1 millisecond**.
11
+
12
+ This is the same pattern AlphaGo used: a big model that thinks about the big picture, and a fast policy network that picks the concrete move. The twist is that for a real-time fighting game, the fast network has to be *really* fast — sub-millisecond per move, on CPU, inside an HF Space.
13
+
14
+ ## How the training worked
15
+
16
+ I trained Nemotron on Modal A100-40GB in three stages:
17
+
18
+ 1. **SFT bootstrap** — 12,000 procedurally generated examples teaching Nemotron to output a JSON of strategic weights given the fight state. Loss went from 2.5 → 2.17 over 3 epochs.
19
+
20
+ 2. **Self-play rollouts** — the SFT model played 100 fights against itself. Each trajectory got a reward: positive for winning trajectories, negative for losing ones. This gave me 106 trajectory points.
21
+
22
+ 3. **Reward-weighted fine-tuning** — I fine-tuned on the self-play data for 3 more epochs, reinforcing high-reward completions and suppressing low-reward ones. This is a simplified version of GRPO that doesn't need the `trl` library.
23
+
24
+ The LoRA adapter is published at [sankalphs/duel-nemotron-strategist](https://huggingface.co/sankalphs/duel-nemotron-strategist).
25
+
26
+ ## How the tiny model works
27
+
28
+ 142,000 parameters. Three-layer MLP with BatchNorm. Input is 168 features: one-hot encodings of the last 5 NPC and 5 player moves, HP and stamina deltas, distance bucket, and the 5 Nemotron strategic weights. Output is 15 move logits (jab, cross, hook, kick, uppercut, block, parry, dodge, advance, retreat, grapple, throw, sweep, feint, wait).
29
+
30
+ Training data: 20,000 procedurally generated (state, strategy) → move examples. Inference: **0.093ms per call on CPU**. The model runs in the HF Space itself — no cloud round-trip for each move.
31
+
32
+ ## What I learned
33
+
34
+ - **Hybrid architectures are underused for real-time games.** A 4B model is great for thinking but terrible for real-time frame-by-frame decisions. A 142k model is the opposite. Pairing them gives you both.
35
+ - **Nemotron is a hybrid Mamba2/Transformer model.** It needs `mamba-ssm` and `causal-conv1d` to run. The Unsloth re-upload is the easiest way to get a working tokenizer config.
36
+ - **HF Spaces have a hard limit of 3 CPU spaces on the free tier.** For production, use the `cpu-upgrade` hardware tier with HF credits.
37
+ - **Binary files don't push via git to HF Spaces.** Use the HF API (`upload_folder`) which uses Xet storage.
38
+ - **Modal cold start is 60–90 seconds for a 4B model.** The Space proxy needs a 120s timeout.
39
+
40
+ ## Try it
41
+
42
+ [Live Space](https://huggingface.co/spaces/sankalphs/duel) · [Fine-tuned adapter](https://huggingface.co/sankalphs/duel-nemotron-strategist) · [Source code](https://github.com/sankalphs/duel)
nemotron-duel/modal/inference_only.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Minimal Modal app: inference only.
2
+ Removes all training/data functions to keep the Modal deployment lean.
3
+ Only the inference web function remains.
4
+ """
5
+ from __future__ import annotations
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+
10
+ import modal
11
+
12
+ MODEL_VOLUME = modal.Volume.from_name("nemotron-duel-models", create_if_missing=False)
13
+ MODEL_PATH = "/vol/models"
14
+
15
+ BASE_MODEL = "unsloth/NVIDIA-Nemotron-3-Nano-4B"
16
+ GPU_INFER = "A10"
17
+
18
+ # Minimal image: just what inference needs (Nemotron + mamba-ssm + causal-conv1d)
19
+ image = (
20
+ modal.Image.from_registry(
21
+ "nvidia/cuda:12.4.0-devel-ubuntu22.04", add_python="3.11"
22
+ )
23
+ .apt_install("git", "gcc", "g++")
24
+ .pip_install("ninja", "packaging", "wheel", "setuptools>=70.1")
25
+ .pip_install(
26
+ "torch==2.5.1",
27
+ "transformers==4.50.0",
28
+ "tokenizers==0.21.4",
29
+ "huggingface_hub>=0.26.0",
30
+ "peft>=0.14.0",
31
+ "accelerate>=0.34.0",
32
+ "starlette>=0.40.0",
33
+ "fastapi>=0.110.0",
34
+ extra_index_url="https://download.pytorch.org/whl/cu124",
35
+ )
36
+ .pip_install(
37
+ "causal-conv1d",
38
+ "mamba-ssm",
39
+ "torch==2.5.1",
40
+ extra_index_url="https://download.pytorch.org/whl/cu124",
41
+ extra_options="--no-build-isolation",
42
+ env={"CC": "gcc", "CXX": "g++", "TORCH_CUDA_ARCH_LIST": "8.6"},
43
+ )
44
+ .env({"HF_HUB_ENABLE_HF_TRANSFER": "1"})
45
+ )
46
+
47
+ app = modal.App("nemotron-duel-inference", image=image)
48
+
49
+
50
+ @app.function(
51
+ volumes={MODEL_PATH: MODEL_VOLUME},
52
+ gpu=GPU_INFER,
53
+ scaledown_window=300,
54
+ secrets=[modal.Secret.from_name("huggingface-secret")],
55
+ )
56
+ @modal.concurrent(max_inputs=10)
57
+ @modal.asgi_app()
58
+ def inference():
59
+ """Serve Nemotron strategist via ASGI on A10 GPU. Inference only."""
60
+ import torch
61
+ from starlette.applications import Starlette
62
+ from starlette.routing import Route
63
+ from starlette.requests import Request
64
+ from starlette.responses import JSONResponse
65
+ from starlette.middleware.cors import CORSMiddleware
66
+ from transformers import AutoModelForCausalLM, AutoTokenizer
67
+ from peft import PeftModel
68
+ from huggingface_hub import login
69
+
70
+ token = os.environ.get("HF_TOKEN")
71
+ if token:
72
+ login(token)
73
+
74
+ _model = None
75
+ _tokenizer = None
76
+
77
+ SYSTEM_PROMPT = (
78
+ "You are an expert fighting game NPC strategist for Duel of Albion. "
79
+ "Based on the fight state (HP, stamina, distance, characters, last 10 moves), "
80
+ "output a JSON object with strategic weight parameters:\n"
81
+ " aggression (0-1), defense (0-1), parry_affinity (0-1), "
82
+ "kick_affinity (0-1), grapple_affinity (0-1), reasoning.\n"
83
+ "Return ONLY the JSON object."
84
+ )
85
+
86
+ def get_model():
87
+ nonlocal _model, _tokenizer
88
+ if _model is None:
89
+ print("Loading Nemotron model (cold start)...")
90
+ adapter_path = Path(MODEL_PATH) / "adapters" / "grpo"
91
+ if not adapter_path.exists():
92
+ adapter_path = Path(MODEL_PATH) / "adapters" / "sft"
93
+
94
+ _tokenizer = AutoTokenizer.from_pretrained(
95
+ BASE_MODEL, cache_dir=MODEL_PATH, token=token, trust_remote_code=True,
96
+ )
97
+ _model = AutoModelForCausalLM.from_pretrained(
98
+ BASE_MODEL, cache_dir=MODEL_PATH, token=token, trust_remote_code=True,
99
+ torch_dtype=torch.bfloat16, device_map="auto",
100
+ )
101
+ if adapter_path.exists():
102
+ _model = PeftModel.from_pretrained(_model, str(adapter_path), token=token)
103
+ _model.eval()
104
+ print("Model loaded!")
105
+ return _model, _tokenizer
106
+
107
+ async def health(request):
108
+ return JSONResponse({"status": "ok", "cold_start": _model is None})
109
+
110
+ async def strategize(request: Request):
111
+ try:
112
+ body = await request.json()
113
+ except Exception:
114
+ body = {}
115
+
116
+ # Accept either {playerChar, npcChar, ...} or {sequence, state} format
117
+ if "sequence" in body or "state" in body:
118
+ state = body.get("state", {})
119
+ sequence = body.get("sequence", "")
120
+ player_char = state.get("playerChar", "ronin")
121
+ npc_char = state.get("npcChar", "brute")
122
+ player_hp = state.get("playerHp", 100)
123
+ npc_hp = state.get("npcHp", 100)
124
+ player_stamina = state.get("playerStamina", 100)
125
+ npc_stamina = state.get("npcStamina", 100)
126
+ round_num = state.get("round", 1)
127
+ distance = state.get("distance", "mid")
128
+ moves = sequence.split() if sequence else state.get("lastMoves", [])
129
+ else:
130
+ player_char = body.get("playerChar", "ronin")
131
+ npc_char = body.get("npcChar", "brute")
132
+ player_hp = body.get("playerHp", 100)
133
+ npc_hp = body.get("npcHp", 100)
134
+ player_stamina = body.get("playerStamina", 100)
135
+ npc_stamina = body.get("npcStamina", 100)
136
+ round_num = body.get("round", 1)
137
+ distance = body.get("distance", "mid")
138
+ moves = body.get("lastMoves", [])
139
+
140
+ moves_str = ", ".join(moves[-10:]) if moves else "none"
141
+
142
+ prompt = (
143
+ f"Round {round_num} | Distance: {distance}\n"
144
+ f"Player ({player_char}): stamina={player_stamina}, hp={player_hp}\n"
145
+ f"NPC ({npc_char}): stamina={npc_stamina}, hp={npc_hp}\n"
146
+ f"Last 10 player moves: {moves_str}\n"
147
+ "Output strategic weights JSON."
148
+ )
149
+
150
+ full = (
151
+ f"<|im_start|>system\n{SYSTEM_PROMPT}<|im_end|>\n"
152
+ f"<|im_start|>user\n{prompt}<|im_end|>\n"
153
+ f"<|im_start|>assistant\n"
154
+ )
155
+
156
+ model, tokenizer = get_model()
157
+ inputs = tokenizer(full, return_tensors="pt").to(model.device)
158
+
159
+ im_end_id = tokenizer.convert_tokens_to_ids("<|im_end|>")
160
+ with torch.no_grad():
161
+ outputs = model.generate(
162
+ **inputs,
163
+ max_new_tokens=200,
164
+ temperature=0.6,
165
+ top_p=0.95,
166
+ do_sample=True,
167
+ pad_token_id=tokenizer.eos_token_id,
168
+ eos_token_id=[tokenizer.eos_token_id, im_end_id],
169
+ )
170
+
171
+ raw = tokenizer.decode(
172
+ outputs[0][inputs["input_ids"].shape[-1]:],
173
+ skip_special_tokens=False,
174
+ ).strip()
175
+
176
+ weights = {
177
+ "aggression": 0.5, "defense": 0.5, "parry_affinity": 0.4,
178
+ "kick_affinity": 0.3, "grapple_affinity": 0.3,
179
+ }
180
+ reasoning = ""
181
+
182
+ def find_first_json(text):
183
+ start = text.find("{")
184
+ if start == -1:
185
+ return None
186
+ depth = 0
187
+ in_str = False
188
+ esc = False
189
+ for i in range(start, len(text)):
190
+ c = text[i]
191
+ if esc:
192
+ esc = False
193
+ continue
194
+ if c == "\\":
195
+ esc = True
196
+ continue
197
+ if c == '"':
198
+ in_str = not in_str
199
+ continue
200
+ if in_str:
201
+ continue
202
+ if c == "{":
203
+ depth += 1
204
+ elif c == "}":
205
+ depth -= 1
206
+ if depth == 0:
207
+ return text[start:i+1]
208
+ return None
209
+
210
+ candidate = find_first_json(raw)
211
+ if candidate:
212
+ try:
213
+ parsed = json.loads(candidate)
214
+ for k in weights:
215
+ weights[k] = float(parsed.get(k, weights[k]))
216
+ reasoning = parsed.get("reasoning", "")
217
+ except (json.JSONDecodeError, ValueError):
218
+ pass
219
+ if not reasoning:
220
+ reasoning = "Using default balanced strategy"
221
+
222
+ return JSONResponse({
223
+ "weights": weights,
224
+ "reasoning": reasoning,
225
+ "raw": raw,
226
+ })
227
+
228
+ api = Starlette(routes=[
229
+ Route("/health", health, methods=["GET"]),
230
+ Route("/strategize", strategize, methods=["POST"]),
231
+ ])
232
+ api.add_middleware(
233
+ CORSMiddleware,
234
+ allow_origins=["*"],
235
+ allow_credentials=True,
236
+ allow_methods=["*"],
237
+ allow_headers=["*"],
238
+ )
239
+ return api