odant-work 1.0.48 → 1.0.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -41,6 +41,106 @@ except Exception:
41
41
  DTYPE_MAP = {}
42
42
 
43
43
 
44
+ _MIOPEN_CPU_FALLBACK_OPS = set()
45
+
46
+
47
+ def _install_rocm_miopen_fallback(target_f=None, target_torch=None):
48
+ """На Windows ROCm (gfx1151) матричные ядра трансформеров (nn.Linear / SDPA) работают на GPU через hipBLASLt,
49
+ но свёрточные ядра MIOpen (Conv1d/Conv2d/ConvTranspose в VAE Z-Image-Turbo и вокодере Qwen3-TTS)
50
+ без компилятора rocm-sdk-devel падают с `miopenStatusInternalError`.
51
+ Прозрачно перехватываем сбойные свёртки MIOpen и выполняем само свёрточное ядро на CPU (Unified Memory),
52
+ возвращая тензор обратно на GPU (`cuda:0`).
53
+ """
54
+ f_mod = target_f if target_f is not None else F
55
+ t_mod = target_torch if target_torch is not None else torch
56
+ if f_mod is None or t_mod is None:
57
+ return False
58
+ if getattr(f_mod, "_work_miopen_wrapped", False):
59
+ return True
60
+ try:
61
+ t_mod.backends.cudnn.benchmark = False
62
+ except Exception:
63
+ pass
64
+
65
+ tensor_cls = getattr(t_mod, "Tensor", None)
66
+ f16_dt = getattr(t_mod, "float16", None)
67
+ f32_dt = getattr(t_mod, "float32", None)
68
+
69
+ def _to_cpu(val):
70
+ if tensor_cls is not None and isinstance(val, tensor_cls):
71
+ dt = f32_dt if (f16_dt is not None and val.dtype == f16_dt and f32_dt is not None) else val.dtype
72
+ return val.to(device="cpu", dtype=dt)
73
+ return val
74
+
75
+ def _wrap_conv(op_name):
76
+ orig_fn = getattr(f_mod, op_name, None)
77
+ if not callable(orig_fn):
78
+ return
79
+
80
+ def _safe_op(*args, **kwargs):
81
+ x = args[0] if args else kwargs.get("input")
82
+ is_cuda = bool(getattr(x, "is_cuda", False))
83
+ if not is_cuda:
84
+ return orig_fn(*args, **kwargs)
85
+ orig_dev = x.device
86
+ orig_dt = getattr(x, "dtype", None)
87
+ key = (op_name, str(orig_dt))
88
+ if key not in _MIOPEN_CPU_FALLBACK_OPS:
89
+ try:
90
+ return orig_fn(*args, **kwargs)
91
+ except Exception as e:
92
+ msg = str(e).lower()
93
+ if "miopen" not in msg and "cudnn" not in msg and "hip" not in msg:
94
+ raise
95
+ _MIOPEN_CPU_FALLBACK_OPS.add(key)
96
+ cpu_args = tuple(_to_cpu(a) for a in args)
97
+ cpu_kwargs = {k: _to_cpu(v) for k, v in kwargs.items()}
98
+ out = orig_fn(*cpu_args, **cpu_kwargs)
99
+ return out.to(device=orig_dev, dtype=orig_dt) if hasattr(out, "to") else out
100
+
101
+ try:
102
+ setattr(f_mod, op_name, _safe_op)
103
+ except Exception:
104
+ pass
105
+ try:
106
+ if hasattr(t_mod, op_name):
107
+ setattr(t_mod, op_name, _safe_op)
108
+ except Exception:
109
+ pass
110
+
111
+ for name in (
112
+ "conv1d",
113
+ "conv2d",
114
+ "conv3d",
115
+ "conv_transpose1d",
116
+ "conv_transpose2d",
117
+ "conv_transpose3d",
118
+ ):
119
+ _wrap_conv(name)
120
+ try:
121
+ f_mod._work_miopen_wrapped = True
122
+ except Exception:
123
+ pass
124
+ return True
125
+
126
+
127
+ if HAS_TORCH:
128
+ _install_rocm_miopen_fallback()
129
+
130
+
131
+ def _is_recoverable_gpu_error(exc):
132
+ msg = str(exc or "").lower()
133
+ return any(tok in msg for tok in (
134
+ "miopen",
135
+ "hip out of memory",
136
+ "cuda out of memory",
137
+ "out of memory",
138
+ "hiperror",
139
+ "cudnn",
140
+ "invalid device function",
141
+ ))
142
+
143
+
44
144
  def _inference_mode_dec():
45
145
  if HAS_TORCH and hasattr(torch, "inference_mode"):
46
146
  return torch.inference_mode()
@@ -294,10 +394,23 @@ def _best_device_and_dtype():
294
394
  "missingDeps": ["torch"],
295
395
  }))
296
396
  if torch.cuda.is_available():
297
- return "cuda", torch.bfloat16
397
+ return "cuda:0", torch.bfloat16
298
398
  return "cpu", (torch.bfloat16 if _cpu_supports_bf16() else torch.float32)
299
399
 
300
400
 
401
+ def _describe_torch_device(device="cpu"):
402
+ dev_str = str(device or "cpu")
403
+ if HAS_TORCH and dev_str.startswith("cuda") and torch.cuda.is_available():
404
+ try:
405
+ name = str(torch.cuda.get_device_name(0) or "").strip()
406
+ return f"GPU ({name})" if name else "GPU"
407
+ except Exception:
408
+ return "GPU"
409
+ if dev_str == "ort":
410
+ return "ONNX (DirectML/NPU)"
411
+ return "CPU (BF16)" if _cpu_supports_bf16() else "CPU"
412
+
413
+
301
414
  def _onnx_external_data_ok(onnx_path):
302
415
  """Внешние тензоры ONNX лежат рядом с графом (`model.onnx_data` / `model.onnx.data`)."""
303
416
  return os.path.isfile(onnx_path + "_data") or os.path.isfile(onnx_path + ".data")
@@ -488,7 +601,7 @@ def handle_embed(req, cache):
488
601
  norms = np.clip(np.linalg.norm(vecs, axis=1, keepdims=True), 1e-12, None)
489
602
  arr = (vecs / norms).tolist()
490
603
  gen_ms = max(1, int((time.time() - t_gen0) * 1000))
491
- return {"embeddings": arr, "dimensions": len(arr[0]) if arr else 0, "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
604
+ return {"embeddings": arr, "dimensions": len(arr[0]) if arr else 0, "device": _describe_torch_device(device), "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
492
605
  with torch.inference_mode():
493
606
  encoded = tok(texts, padding=True, truncation=True, max_length=int(req.get("maxLength", 2048)), return_tensors="pt")
494
607
  encoded = {k: v.to(device) for k, v in encoded.items()}
@@ -500,7 +613,7 @@ def handle_embed(req, cache):
500
613
  vecs = F.normalize(summed / counts, p=2, dim=1)
501
614
  arr = vecs.cpu().tolist()
502
615
  gen_ms = max(1, int((time.time() - t_gen0) * 1000))
503
- return {"embeddings": arr, "dimensions": len(arr[0]) if arr else 0, "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
616
+ return {"embeddings": arr, "dimensions": len(arr[0]) if arr else 0, "device": _describe_torch_device(device), "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
504
617
 
505
618
 
506
619
  def _load_rerank_model(weights_dir, cache):
@@ -575,7 +688,7 @@ def handle_rerank(req, cache):
575
688
  if top_n > 0:
576
689
  ranked = ranked[:top_n]
577
690
  gen_ms = max(1, int((time.time() - t_gen0) * 1000))
578
- return {"results": ranked, "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
691
+ return {"results": ranked, "device": _describe_torch_device(device), "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
579
692
 
580
693
 
581
694
  def _load_image_pipeline(weights_dir, cache):
@@ -601,7 +714,16 @@ def _load_image_pipeline(weights_dir, cache):
601
714
  pipe = None
602
715
  if pipe is None:
603
716
  pipe = diffusers.AutoPipelineForText2Image.from_pretrained(weights_dir, local_files_only=True, torch_dtype=dtype)
604
- pipe.to(device)
717
+ try:
718
+ pipe.to(device)
719
+ except Exception:
720
+ if str(device).startswith("cuda") and HAS_TORCH:
721
+ try:
722
+ torch.cuda.empty_cache()
723
+ except Exception:
724
+ pass
725
+ device = "cpu"
726
+ pipe.to(device)
605
727
  cache[key] = (pipe, device)
606
728
  return cache[key]
607
729
 
@@ -626,13 +748,29 @@ def handle_image(req, cache):
626
748
  kwargs = {"prompt": prompt, "width": w, "height": h, "num_inference_steps": steps, "generator": gen}
627
749
  if is_turbo:
628
750
  kwargs["guidance_scale"] = 0.0
629
- with torch.inference_mode():
630
- out = pipe(**kwargs)
631
- img = out.images[0]
751
+ try:
752
+ with torch.inference_mode():
753
+ out = pipe(**kwargs)
754
+ img = out.images[0]
755
+ except Exception as e:
756
+ if str(device).startswith("cuda") and _is_recoverable_gpu_error(e):
757
+ try:
758
+ torch.cuda.empty_cache()
759
+ except Exception:
760
+ pass
761
+ device = "cpu"
762
+ pipe.to("cpu")
763
+ cache[("image", weights_dir)] = (pipe, "cpu")
764
+ kwargs["generator"] = torch.Generator(device="cpu").manual_seed(seed)
765
+ with torch.inference_mode():
766
+ out = pipe(**kwargs)
767
+ img = out.images[0]
768
+ else:
769
+ raise
632
770
  buf = io.BytesIO()
633
771
  img.save(buf, format="PNG")
634
772
  gen_ms = max(1, int((time.time() - t_gen0) * 1000))
635
- return {"mime": "image/png", "base64": base64.b64encode(buf.getvalue()).decode("ascii"), "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
773
+ return {"mime": "image/png", "base64": base64.b64encode(buf.getvalue()).decode("ascii"), "device": _describe_torch_device(device), "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
636
774
 
637
775
 
638
776
  def _pcm_to_wav_base64(samples, sample_rate):
@@ -871,11 +1009,138 @@ def _seed_torch_deterministic(seed_val):
871
1009
  pass
872
1010
 
873
1011
 
1012
+ def _install_fast_qwen_tts_code_predictor(mdl):
1013
+ """Ускоряет внутренний 15-шаговый цикл `code_predictor` в Qwen3-TTS (вызывается на каждом 12 Гц кадре).
1014
+
1015
+ Штатный `qwen_tts` на каждом 12 Гц шаге вызывает полный `GenerationMixin.generate()`,
1016
+ делая `deepcopy(generation_config)`, `torch.sort` по всему словарю и сохраняя 75 неиспользуемых
1017
+ тензоров `output_hidden_states=True`. Прямой цикл по 15 головам `lm_head[step]` делает ту же
1018
+ математику без обвязки `GenerationMixin` и лишних аллокаций.
1019
+ """
1020
+ cp = getattr(getattr(getattr(mdl, "model", None), "talker", None), "code_predictor", None)
1021
+ if cp is None or getattr(cp, "_work_fast_patched", False):
1022
+ return
1023
+ orig_generate = cp.generate
1024
+
1025
+ class _FastPredictorOut:
1026
+ __slots__ = ("sequences", "hidden_states")
1027
+
1028
+ def __init__(self, sequences):
1029
+ self.sequences = sequences
1030
+ self.hidden_states = None
1031
+
1032
+ def _fast_generate(
1033
+ inputs_embeds=None,
1034
+ max_new_tokens=None,
1035
+ do_sample=False,
1036
+ top_p=1.0,
1037
+ top_k=50,
1038
+ temperature=0.9,
1039
+ **kwargs,
1040
+ ):
1041
+ if inputs_embeds is None:
1042
+ return orig_generate(
1043
+ inputs_embeds=inputs_embeds,
1044
+ max_new_tokens=max_new_tokens,
1045
+ do_sample=do_sample,
1046
+ top_p=top_p,
1047
+ top_k=top_k,
1048
+ temperature=temperature,
1049
+ **kwargs,
1050
+ )
1051
+ try:
1052
+ from transformers.cache_utils import DynamicCache
1053
+ steps = int(max_new_tokens or (cp.config.num_code_groups - 1))
1054
+ past_kv = DynamicCache()
1055
+ cur_embeds = cp.small_to_mtp_projection(inputs_embeds)
1056
+ embs = cp.model.get_input_embeddings()
1057
+ heads = cp.lm_head
1058
+ tokens = []
1059
+ temp = float(temperature) if (temperature and float(temperature) > 0) else 1.0
1060
+ k = int(top_k) if top_k else 0
1061
+ for step in range(steps):
1062
+ out = cp.model(
1063
+ input_ids=None,
1064
+ inputs_embeds=cur_embeds,
1065
+ past_key_values=past_kv,
1066
+ use_cache=True,
1067
+ output_attentions=False,
1068
+ output_hidden_states=False,
1069
+ )
1070
+ last_h = out.last_hidden_state[:, -1, :]
1071
+ logits = heads[step](last_h)
1072
+ if not do_sample:
1073
+ next_tok = torch.argmax(logits, dim=-1, keepdim=True)
1074
+ else:
1075
+ if temp != 1.0:
1076
+ logits = logits / temp
1077
+ if 0 < k < logits.size(-1):
1078
+ top_vals, top_idx = torch.topk(logits, k, dim=-1)
1079
+ probs = F.softmax(top_vals, dim=-1)
1080
+ pick = torch.multinomial(probs, num_samples=1)
1081
+ next_tok = top_idx.gather(-1, pick)
1082
+ else:
1083
+ probs = F.softmax(logits, dim=-1)
1084
+ next_tok = torch.multinomial(probs, num_samples=1)
1085
+ tokens.append(next_tok)
1086
+ if step + 1 < steps:
1087
+ cur_embeds = cp.small_to_mtp_projection(embs[step](next_tok))
1088
+ return _FastPredictorOut(torch.cat(tokens, dim=-1))
1089
+ except Exception:
1090
+ return orig_generate(
1091
+ inputs_embeds=inputs_embeds,
1092
+ max_new_tokens=max_new_tokens,
1093
+ do_sample=do_sample,
1094
+ top_p=top_p,
1095
+ top_k=top_k,
1096
+ temperature=temperature,
1097
+ **kwargs,
1098
+ )
1099
+
1100
+ cp.generate = _fast_generate
1101
+ cp._work_fast_patched = True
1102
+
1103
+
874
1104
  def _call_tts_gen(fn, max_new_tokens, **kwargs):
875
1105
  try:
876
- return fn(max_new_tokens=max_new_tokens, **kwargs)
1106
+ return fn(max_new_tokens=max_new_tokens, subtalker_dosample=False, **kwargs)
877
1107
  except TypeError:
878
- return fn(**kwargs)
1108
+ try:
1109
+ return fn(max_new_tokens=max_new_tokens, **kwargs)
1110
+ except TypeError:
1111
+ return fn(**kwargs)
1112
+
1113
+
1114
+ def _load_qwen_tts_model(weights_dir):
1115
+ from qwen_tts import Qwen3TTSModel
1116
+ device, dtype = _best_device_and_dtype()
1117
+ candidates = [(device, dtype)]
1118
+ if str(device).startswith("cuda"):
1119
+ cpu_dtype = torch.bfloat16 if _cpu_supports_bf16() else torch.float32
1120
+ candidates.append(("cpu", cpu_dtype))
1121
+ last_err = None
1122
+ for dev, dt in candidates:
1123
+ try:
1124
+ try:
1125
+ mdl = Qwen3TTSModel.from_pretrained(
1126
+ weights_dir,
1127
+ device_map=dev,
1128
+ dtype=dt,
1129
+ attn_implementation="sdpa",
1130
+ )
1131
+ except Exception:
1132
+ mdl = Qwen3TTSModel.from_pretrained(weights_dir, device_map=dev, dtype=dt)
1133
+ _install_fast_qwen_tts_code_predictor(mdl)
1134
+ mdl._work_device = dev
1135
+ return mdl
1136
+ except Exception as e:
1137
+ last_err = e
1138
+ if str(dev).startswith("cuda") and HAS_TORCH:
1139
+ try:
1140
+ torch.cuda.empty_cache()
1141
+ except Exception:
1142
+ pass
1143
+ raise last_err
879
1144
 
880
1145
 
881
1146
  def handle_tts(req, cache):
@@ -884,39 +1149,31 @@ def handle_tts(req, cache):
884
1149
  language = _tts_language(req.get("language") or "Russian")
885
1150
  instructions = str(req.get("instructions") or "").strip()
886
1151
  seed = int(req.get("seed") if req.get("seed") is not None else 42)
887
- # 12 Гц аудио-токенизатор: динамический потолок шагов декодера под реальную длину текста
888
- max_new_tokens = max(128, min(1024, int(len(text) * 4.5) + 96))
1152
+ # 12.5 Гц аудио-токенизатор (~0.93 кадра на символ речи): компактный потолок без холостых хвостов
1153
+ max_new_tokens = max(72, min(768, int(len(text) * 2.0) + 48))
889
1154
  key = ("tts", weights_dir)
890
1155
  was_cached = key in cache
891
1156
  t_load0 = time.time()
892
1157
  if not was_cached:
893
1158
  try:
894
- from qwen_tts import Qwen3TTSModel
1159
+ from qwen_tts import Qwen3TTSModel # noqa: F401
895
1160
  except Exception as e:
896
1161
  raise RuntimeError(json.dumps(_missing_pkg_error(e, {
897
1162
  "qwen_tts": "qwen-tts",
898
1163
  "soundfile": "soundfile",
899
1164
  })))
900
- device, dtype = _best_device_and_dtype()
901
1165
  try:
902
- try:
903
- mdl = Qwen3TTSModel.from_pretrained(
904
- weights_dir,
905
- device_map=device,
906
- dtype=dtype,
907
- attn_implementation="sdpa",
908
- )
909
- except Exception:
910
- mdl = Qwen3TTSModel.from_pretrained(weights_dir, device_map=device, dtype=dtype)
1166
+ cache[key] = _load_qwen_tts_model(weights_dir)
911
1167
  except Exception as e:
912
1168
  # Пакет установлен, но веса/конфиг не читаются — отдаём реальную причину,
913
1169
  # а не ложное «нет пакетов», из-за которого раньше шёл бесконечный переустанов.
914
1170
  raise RuntimeError(json.dumps({
915
1171
  "error": f"Не удалось загрузить модель синтеза речи из {weights_dir}: {e}",
916
1172
  }))
917
- cache[key] = mdl
918
1173
  load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
919
1174
  mdl = cache[key]
1175
+ _install_fast_qwen_tts_code_predictor(mdl)
1176
+ active_dev = getattr(mdl, "_work_device", None) or str(getattr(mdl, "device", "cpu"))
920
1177
  kind = _tts_model_kind(weights_dir, mdl, instructions)
921
1178
  _seed_torch_deterministic(seed)
922
1179
  t_gen0 = time.time()
@@ -993,6 +1250,7 @@ def handle_tts(req, cache):
993
1250
  "sampleRate": int(sr),
994
1251
  "ttsKind": kind,
995
1252
  "instructUsed": instruct_used,
1253
+ "device": _describe_torch_device(active_dev),
996
1254
  "loadMs": load_ms,
997
1255
  "genMs": gen_ms,
998
1256
  "durationMs": gen_ms,
@@ -1009,31 +1267,47 @@ def handle_stt(req, cache):
1009
1267
  t_load0 = time.time()
1010
1268
  if not was_cached:
1011
1269
  device, dtype = _best_device_and_dtype()
1270
+ candidates = [(device, dtype)]
1271
+ if str(device).startswith("cuda"):
1272
+ cpu_dtype = torch.bfloat16 if _cpu_supports_bf16() else torch.float32
1273
+ candidates.append(("cpu", cpu_dtype))
1012
1274
  errors = []
1013
1275
  try:
1014
1276
  from qwen_asr import Qwen3ASRModel
1015
- try:
1277
+ for dev, dt in candidates:
1016
1278
  try:
1017
- loaded = Qwen3ASRModel.from_pretrained(weights_dir, dtype=dtype, device_map=device, attn_implementation="sdpa")
1018
- except Exception:
1019
- loaded = Qwen3ASRModel.from_pretrained(weights_dir, dtype=dtype, device_map=device)
1020
- cache[key] = ("qwen_asr", loaded)
1021
- except Exception as e:
1022
- errors.append(f"qwen-asr: {e}")
1279
+ try:
1280
+ loaded = Qwen3ASRModel.from_pretrained(weights_dir, dtype=dt, device_map=dev, attn_implementation="sdpa")
1281
+ except Exception:
1282
+ loaded = Qwen3ASRModel.from_pretrained(weights_dir, dtype=dt, device_map=dev)
1283
+ loaded._work_device = dev
1284
+ cache[key] = ("qwen_asr", loaded)
1285
+ break
1286
+ except Exception as e:
1287
+ errors.append(f"qwen-asr ({dev}): {e}")
1288
+ if str(dev).startswith("cuda") and HAS_TORCH:
1289
+ try:
1290
+ torch.cuda.empty_cache()
1291
+ except Exception:
1292
+ pass
1023
1293
  except Exception as e:
1024
1294
  errors.append(f"qwen-asr (нет пакета): {e}")
1025
1295
  if key not in cache:
1026
1296
  try:
1027
1297
  from transformers import pipeline
1028
- try:
1029
- cache[key] = ("hf_asr", pipeline(
1030
- "automatic-speech-recognition",
1031
- model=weights_dir,
1032
- device=0 if device == "cuda" else -1,
1033
- torch_dtype=dtype,
1034
- ))
1035
- except Exception as e:
1036
- errors.append(f"transformers: {e}")
1298
+ for dev, dt in candidates:
1299
+ try:
1300
+ p_obj = pipeline(
1301
+ "automatic-speech-recognition",
1302
+ model=weights_dir,
1303
+ device=0 if str(dev).startswith("cuda") else -1,
1304
+ torch_dtype=dt,
1305
+ )
1306
+ p_obj._work_device = dev
1307
+ cache[key] = ("hf_asr", p_obj)
1308
+ break
1309
+ except Exception as e:
1310
+ errors.append(f"transformers ({dev}): {e}")
1037
1311
  except Exception as e:
1038
1312
  errors.append(f"transformers (нет пакета): {e}")
1039
1313
  if key not in cache:
@@ -1049,6 +1323,7 @@ def handle_stt(req, cache):
1049
1323
  }))
1050
1324
  load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
1051
1325
  kind, mdl = cache[key]
1326
+ active_dev = getattr(mdl, "_work_device", None) or str(getattr(mdl, "device", "cpu"))
1052
1327
  import tempfile
1053
1328
  with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tf:
1054
1329
  tf.write(raw)
@@ -1073,7 +1348,7 @@ def handle_stt(req, cache):
1073
1348
  except Exception:
1074
1349
  pass
1075
1350
  gen_ms = max(1, int((time.time() - t_gen0) * 1000))
1076
- return {"text": str(txt or "").strip(), "language": language or "Auto", "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
1351
+ return {"text": str(txt or "").strip(), "language": language or "Auto", "device": _describe_torch_device(active_dev), "loadMs": load_ms, "genMs": gen_ms, "durationMs": gen_ms}
1077
1352
 
1078
1353
 
1079
1354
  def main():