Rabius commited on
Commit
20af968
·
verified ·
1 Parent(s): c4ec3a7

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +188 -26
README.md CHANGED
@@ -41,39 +41,201 @@ We can divide the required dataset into the following categories.
41
  As Qwen3 -4B is a small model, around 20k - 25k examples is enough to fine tune the model in 2. Bengali cultural alignment, 3.Toxicity refusal (Bengali), 4. Cross-lingual instruction data. We can source existing dataset and translate them into multilingual dataset. The main problem of translation is that it doesn't align well with naturalness and cultural adaptation. So I have to find a way to do it.
42
  For 1 . Multilingual CoT reasoning, fine tuning with translated Math or IMO problems could be a solution. Maybe we can use LoRa, but the problem is, the model will probably struggle in unseen new problems. This is an active research domain, so I need help here.
43
 
44
- ## 🔗 Model & Loading
45
- The model tested is **[Qwen/Qwen3-4B](https://huggingface.co/Qwen/Qwen3-4B)**.
46
-
47
- This code is the sample code provided by Qwen3-4B repo.
48
- To reproduce these results, the model was loaded in `float16` to balance performance and memory.
49
 
50
 
51
  ```python
52
- from transformers import AutoTokenizer, AutoModelForCausalLM
 
 
 
 
 
 
 
 
 
 
53
  import torch
 
 
54
 
55
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
56
- tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-4B")
 
57
 
58
- model = AutoModelForCausalLM.from_pretrained(
59
- "Qwen/Qwen3-4B",
60
- torch_dtype=torch.float16,
61
- device_map="auto"
 
 
 
62
  )
63
- model.eval()
64
 
65
- def ask(prompt):
66
- messages = [{"role": "user", "content": prompt}]
67
- text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
68
- inputs = tokenizer([text], return_tensors="pt").to(model.device)
69
- outputs = model.generate(**inputs, max_new_tokens=2048)
70
- generated_tokens = outputs[0][inputs.input_ids.shape[-1]:]
71
- output_ids = generated_tokens.tolist()
72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  try:
74
- # Skip internal thinking block
75
- index = len(output_ids) - output_ids[::-1].index(151668)
76
- except ValueError:
77
- index = 0
78
-
79
- return tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  As Qwen3 -4B is a small model, around 20k - 25k examples is enough to fine tune the model in 2. Bengali cultural alignment, 3.Toxicity refusal (Bengali), 4. Cross-lingual instruction data. We can source existing dataset and translate them into multilingual dataset. The main problem of translation is that it doesn't align well with naturalness and cultural adaptation. So I have to find a way to do it.
42
  For 1 . Multilingual CoT reasoning, fine tuning with translated Math or IMO problems could be a solution. Maybe we can use LoRa, but the problem is, the model will probably struggle in unseen new problems. This is an active research domain, so I need help here.
43
 
44
+ ## 🔗 Inference on Dataset
 
 
 
 
45
 
46
 
47
  ```python
48
+
49
+ import argparse
50
+ import contextlib
51
+ import csv
52
+ import re
53
+ import shutil
54
+ import sys
55
+ import tempfile
56
+ import time
57
+ from pathlib import Path
58
+
59
  import torch
60
+ import transformers
61
+ from huggingface_hub import HfApi, HfFileSystem
62
 
63
+ MODEL_NAME = "nvidia/Cosmos-Reason2-2B"
64
+ DATASET_ID = "Rabius/Navigation_Benchmark"
65
+ DEFAULT_PROMPT = "Describe what is happening and what the robot should do next."
66
 
67
+ IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp"}
68
+ VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv"}
69
+
70
+ THINK_SUFFIX = (
71
+ "\n\nAnswer the question using the following format:\n\n"
72
+ "<think>\nYour reasoning.\n</think>\n\n"
73
+ "Write your final answer immediately after the </think> tag."
74
  )
 
75
 
 
 
 
 
 
 
 
76
 
77
+ def natural_key(path: Path):
78
+ return [int(t) if t.isdigit() else t.lower() for t in re.split(r"(\d+)", path.name)]
79
+
80
+
81
+ def collect_local(root: Path, include_poster: bool):
82
+ """(kind, Path) for images/ and videos/ in a local copy of the dataset."""
83
+ items = []
84
+ for folder, exts, kind in (("images", IMAGE_EXTS, "image"), ("videos", VIDEO_EXTS, "video")):
85
+ d = root / folder
86
+ if d.exists():
87
+ files = sorted(
88
+ (p for p in d.rglob("*") if p.is_file() and p.suffix.lower() in exts),
89
+ key=natural_key,
90
+ )
91
+ items += [(kind, p) for p in files]
92
+ if include_poster and (root / "poster.jpg").exists():
93
+ items.append(("image", root / "poster.jpg"))
94
+ return items
95
+
96
+
97
+ def collect_remote(include_poster: bool):
98
+ """(kind, repo_path) for images/ and videos/ listed straight from the Hub (no download)."""
99
+ repo_files = HfApi().list_repo_files(DATASET_ID, repo_type="dataset")
100
+ items = []
101
+ for folder, exts, kind in (("images", IMAGE_EXTS, "image"), ("videos", VIDEO_EXTS, "video")):
102
+ paths = sorted(
103
+ (p for p in repo_files if p.startswith(folder + "/") and Path(p).suffix.lower() in exts),
104
+ key=lambda p: natural_key(Path(p)),
105
+ )
106
+ items += [(kind, p) for p in paths]
107
+ if include_poster and "poster.jpg" in repo_files:
108
+ items.append(("image", "poster.jpg"))
109
+ return items
110
+
111
+
112
+ @contextlib.contextmanager
113
+ def materialize(source, fs, tmpdir):
114
+
115
+ if isinstance(source, Path):
116
+ yield source
117
+ return
118
+ dst = Path(tmpdir) / Path(source).name
119
+ with fs.open(f"datasets/{DATASET_ID}/{source}", "rb") as src, open(dst, "wb") as out:
120
+ shutil.copyfileobj(src, out)
121
  try:
122
+ yield dst
123
+ finally:
124
+ dst.unlink(missing_ok=True)
125
+
126
+
127
+ def build_messages(kind: str, path: Path, prompt: str, fps: int, think: bool):
128
+ text = prompt + (THINK_SUFFIX if think else "")
129
+ if kind == "image":
130
+ media = {"type": "image", "image": str(path.resolve())}
131
+ else:
132
+ media = {"type": "video", "video": str(path.resolve()), "fps": fps}
133
+ return [
134
+ {"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant."}]},
135
+ {"role": "user", "content": [media, {"type": "text", "text": text}]},
136
+ ]
137
+
138
+
139
+ def extract_answer(text: str) -> str:
140
+ """Pull the final answer out of '<think>...</think><answer>...</answer>' style output."""
141
+ m = re.search(r"<answer>(.*?)(?:</answer>|$)", text, flags=re.S)
142
+ if m:
143
+ return m.group(1).strip()
144
+ if "</think>" in text:
145
+ return text.split("</think>")[-1].strip()
146
+ return text.strip()
147
+
148
+
149
+ @torch.inference_mode()
150
+ def run_one(model, processor, kind, path, prompt, fps, max_new_tokens, think):
151
+ messages = build_messages(kind, path, prompt, fps, think)
152
+ kwargs = {"fps": fps} if kind == "video" else {}
153
+ inputs = processor.apply_chat_template(
154
+ messages,
155
+ tokenize=True,
156
+ add_generation_prompt=True,
157
+ return_dict=True,
158
+ return_tensors="pt",
159
+ **kwargs,
160
+ ).to(model.device)
161
+
162
+ generated = model.generate(**inputs, max_new_tokens=max_new_tokens)
163
+ trimmed = [out[len(inp):] for inp, out in zip(inputs.input_ids, generated)]
164
+ text = processor.batch_decode(
165
+ trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
166
+ )[0]
167
+ return text.strip()
168
+
169
+
170
+ def main():
171
+ ap = argparse.ArgumentParser(description="Cosmos-Reason2-2B batch inference -> CSV")
172
+ ap.add_argument("--prompt", default=DEFAULT_PROMPT)
173
+ ap.add_argument("--output", default="cosmos_reason2_outputs.csv")
174
+ ap.add_argument("--data-dir", default=None,
175
+ help="Use a local copy of the dataset instead of streaming from the Hub.")
176
+ ap.add_argument("--fps", type=int, default=4, help="Video sampling FPS (model card: 4). Lower it if you run out of VRAM.")
177
+ ap.add_argument("--max-new-tokens", type=int, default=1024,
178
+ help="Default 1024 is plenty for short answers; use 4096+ with --think.")
179
+ ap.add_argument("--think", action="store_true",
180
+ help="Ask for <think> reasoning and also save it in a full_output column (slower, longer).")
181
+ ap.add_argument("--include-poster", action="store_true", help="Also run poster.jpg from the dataset root.")
182
+ args = ap.parse_args()
183
+
184
+ if not torch.cuda.is_available():
185
+ sys.exit("No CUDA GPU detected. This script needs a GPU.")
186
+
187
+ # ---- Data ----
188
+ fs = HfFileSystem()
189
+ if args.data_dir:
190
+ media = collect_local(Path(args.data_dir), args.include_poster)
191
+ else:
192
+ print(f"Listing {DATASET_ID} on the Hub (streaming, no full download) ...")
193
+ media = collect_remote(args.include_poster)
194
+ if not media:
195
+ sys.exit("No images/videos found.")
196
+ print(f"Found {sum(k == 'image' for k, _ in media)} images and "
197
+ f"{sum(k == 'video' for k, _ in media)} videos.")
198
+
199
+ # ---- Model ----
200
+ dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
201
+ print(f"Loading {MODEL_NAME} ({dtype}) on {torch.cuda.get_device_name(0)} ...")
202
+ model = transformers.Qwen3VLForConditionalGeneration.from_pretrained(
203
+ MODEL_NAME, dtype=dtype, device_map="auto", attn_implementation="sdpa"
204
+ )
205
+ model.eval()
206
+ processor = transformers.AutoProcessor.from_pretrained(MODEL_NAME)
207
+
208
+ # ---- Inference ----
209
+ think = args.think
210
+ with tempfile.TemporaryDirectory() as tmpdir, \
211
+ open(args.output, "w", newline="", encoding="utf-8-sig") as f:
212
+ writer = csv.writer(f)
213
+ writer.writerow(["name", "type", "prompt", "answer"] + (["full_output"] if think else []))
214
+
215
+ for i, (kind, source) in enumerate(media, 1):
216
+ name = Path(source).name
217
+ print(f"[{i}/{len(media)}] {kind}: {name} ...", end=" ", flush=True)
218
+ t0 = time.time()
219
+ try:
220
+ with materialize(source, fs, tmpdir) as local_path:
221
+ full = run_one(model, processor, kind, local_path, args.prompt,
222
+ args.fps, args.max_new_tokens, think)
223
+ answer = extract_answer(full)
224
+ print(f"done ({time.time() - t0:.1f}s)")
225
+ except torch.cuda.OutOfMemoryError:
226
+ full = answer = "ERROR: CUDA out of memory (try a lower --fps or --max-new-tokens)"
227
+ print("OOM")
228
+ except Exception as e: # keep going so one bad file doesn't kill the run
229
+ full = answer = f"ERROR: {type(e).__name__}: {e}"
230
+ print("failed")
231
+ finally:
232
+ torch.cuda.empty_cache()
233
+
234
+ writer.writerow([name, kind, args.prompt, answer] + ([full] if think else []))
235
+ f.flush() # results are saved as we go
236
+
237
+ print(f"\nSaved {len(media)} rows to {Path(args.output).resolve()}")
238
+
239
+
240
+ if __name__ == "__main__":
241
+ main()