Skip to content

Commit db0ae40

Browse files
rui-renjustinchubyruiren_microsoft
authored
support multi gpu for golden dataset generation (#222)
Auto detect `gpu` when generating dataset. --------- Co-authored-by: Justin Chu <[email protected]> Co-authored-by: ruiren_microsoft <[email protected]>
1 parent a8e4ca2 commit db0ae40

1 file changed

Lines changed: 52 additions & 13 deletions

File tree

‎scripts/generate_golden.py‎

Lines changed: 52 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,25 @@ def _patched_prepare(input_ids, **kwargs):
180180
model.prepare_inputs_for_generation = _patched_prepare
181181

182182

183+
# ---- Device helpers ----
184+
185+
186+
def _get_model_device(model: object, device: str):
187+
"""Return the concrete ``torch.device`` where model inputs should go.
188+
189+
``device_map="auto"`` is valid for ``from_pretrained()`` (it
190+
distributes layers across available GPUs), but ``.to("auto")`` is
191+
not valid for tensors or BatchEncoding objects. When *device* is
192+
``"auto"``, we inspect the model's first parameter to find the
193+
actual device that inputs should be placed on.
194+
"""
195+
import torch
196+
197+
if device == "auto":
198+
return next(model.parameters()).device
199+
return torch.device(device)
200+
201+
183202
# ---- Task-specific generators ----
184203
# Each generator loads a HF model, runs inference, and calls
185204
# save_golden_ref() from golden.py. Heavy imports (torch,
@@ -214,9 +233,10 @@ def _generate_causal_lm(case: TestCase, json_path: Path, device: str) -> None:
214233

215234
_apply_nemotron_h_generate_patch(model)
216235

236+
model_device = _get_model_device(model, device)
217237
with torch.no_grad():
218238
gen_output = model.generate(
219-
torch.from_numpy(input_ids).to(device),
239+
torch.from_numpy(input_ids).to(model_device),
220240
max_new_tokens=case.generation_params.get("max_new_tokens", 20),
221241
do_sample=False,
222242
)
@@ -392,7 +412,14 @@ def _generate_vision_language(case: TestCase, json_path: Path, device: str) -> N
392412
text=prompt_text,
393413
images=images if images else None,
394414
return_tensors="pt",
395-
).to(device)
415+
)
416+
417+
# Normalize the CLI/device-map selection to a concrete runtime device
418+
# before moving any tensors. `device="auto"` is handled by Transformers/
419+
# Accelerate during model loading, but `.to("auto")` is not valid for
420+
# BatchEncoding or Tensor objects.
421+
model_device = _get_model_device(model, device)
422+
processed = processed.to(model_device)
396423

397424
# L4: single forward pass
398425
with torch.no_grad():
@@ -456,16 +483,19 @@ def _generate_speech_to_text(case: TestCase, json_path: Path, device: str) -> No
456483
# Load and preprocess audio
457484
audio_path = Path("testdata") / case.audio[0]
458485
audio_array, sample_rate = librosa.load(str(audio_path), sr=16000)
486+
model_device = _get_model_device(model, device)
459487
processed = processor(audio_array, sampling_rate=sample_rate, return_tensors="pt").to(
460-
device
488+
model_device
461489
)
462490
input_features = processed["input_features"]
463491

464492
# L4: single decoder step with forced decoder start token
465493
decoder_start_id = (
466494
model.config.decoder_start_token_id or model.generation_config.decoder_start_token_id
467495
)
468-
decoder_input_ids = torch.tensor([[decoder_start_id]], dtype=torch.long, device=device)
496+
decoder_input_ids = torch.tensor(
497+
[[decoder_start_id]], dtype=torch.long, device=model_device
498+
)
469499
with torch.no_grad():
470500
outputs = model(
471501
input_features=input_features,
@@ -625,10 +655,16 @@ def _load_speech_language_model(case: TestCase, device: str) -> tuple:
625655
Qwen3ASRForConditionalGeneration,
626656
)
627657

628-
model = Qwen3ASRForConditionalGeneration.from_pretrained(
629-
case.model_id, torch_dtype=torch.float32
630-
)
631-
model = model.to(device).eval()
658+
if device == "auto":
659+
model = Qwen3ASRForConditionalGeneration.from_pretrained(
660+
case.model_id, torch_dtype=torch.float32, device_map=device
661+
)
662+
else:
663+
model = Qwen3ASRForConditionalGeneration.from_pretrained(
664+
case.model_id, torch_dtype=torch.float32
665+
)
666+
model = model.to(device)
667+
model.eval()
632668
processor = transformers.AutoProcessor.from_pretrained(
633669
case.model_id, trust_remote_code=True
634670
)
@@ -684,11 +720,12 @@ def _prepare_speech_language_inputs(
684720
if case.prompts:
685721
force_prefix = case.prompts[0]
686722
text_prompt = text_prompt + force_prefix
723+
model_device = _get_model_device(model, device)
687724
processed = processor(
688725
text=text_prompt,
689726
audio=[audio_array],
690727
return_tensors="pt",
691-
).to(device)
728+
).to(model_device)
692729
prompt_for_golden = force_prefix or str(audio_path)
693730
else:
694731
# Gemma4-style: text prompt + audio
@@ -702,11 +739,12 @@ def _prepare_speech_language_inputs(
702739
prompt_text = processor.apply_chat_template(
703740
messages, tokenize=False, add_generation_prompt=True
704741
)
742+
model_device = _get_model_device(model, device)
705743
processed = processor(
706744
text=prompt_text,
707745
audio=[audio_array],
708746
return_tensors="pt",
709-
).to(device)
747+
).to(model_device)
710748
prompt_for_golden = case.prompts[0]
711749

712750
return processed, prompt_for_golden
@@ -1047,7 +1085,8 @@ def _generate_phi4mm_multimodal(case: TestCase, json_path: Path, device: str) ->
10471085
call_kwargs["audios"] = audios
10481086
call_kwargs["return_tensors"] = "pt"
10491087

1050-
processed = processor(**call_kwargs).to(device)
1088+
model_device = _get_model_device(model, device)
1089+
processed = processor(**call_kwargs).to(model_device)
10511090

10521091
# L4: single forward pass for prefill logits
10531092
with torch.no_grad():
@@ -1087,13 +1126,13 @@ def _generate_phi4mm_multimodal(case: TestCase, json_path: Path, device: str) ->
10871126
1,
10881127
kv_len + 1,
10891128
dtype=torch.long,
1090-
device=device,
1129+
device=model_device,
10911130
),
10921131
)
10931132
next_id = int(out.logits[0, -1, :].argmax())
10941133
past_kv = out.past_key_values
10951134
gen_ids.append(next_id)
1096-
cur_input_ids = torch.tensor([[next_id]], dtype=torch.long, device=device)
1135+
cur_input_ids = torch.tensor([[next_id]], dtype=torch.long, device=model_device)
10971136
# Stop on EOS
10981137
eos = getattr(model.config, "eos_token_id", None)
10991138
if eos is not None and next_id == eos:

0 commit comments

Comments
 (0)