odant-work 1.0.49 → 1.0.51

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.
@@ -5,6 +5,8 @@
5
5
  Общается с Node.js-сервером WORK по протоколу JSONL (stdin -> stdout), удерживая веса модели в памяти между запросами.
6
6
  """
7
7
  import base64
8
+ import ctypes
9
+ import gc
8
10
  import glob
9
11
  import io
10
12
  import json
@@ -12,6 +14,7 @@ import mmap
12
14
  import os
13
15
  import struct
14
16
  import sys
17
+ import threading
15
18
  import time
16
19
  import warnings
17
20
  import wave
@@ -41,6 +44,106 @@ except Exception:
41
44
  DTYPE_MAP = {}
42
45
 
43
46
 
47
+ _MIOPEN_CPU_FALLBACK_OPS = set()
48
+
49
+
50
+ def _install_rocm_miopen_fallback(target_f=None, target_torch=None):
51
+ """На Windows ROCm (gfx1151) матричные ядра трансформеров (nn.Linear / SDPA) работают на GPU через hipBLASLt,
52
+ но свёрточные ядра MIOpen (Conv1d/Conv2d/ConvTranspose в VAE Z-Image-Turbo и вокодере Qwen3-TTS)
53
+ без компилятора rocm-sdk-devel падают с `miopenStatusInternalError`.
54
+ Прозрачно перехватываем сбойные свёртки MIOpen и выполняем само свёрточное ядро на CPU (Unified Memory),
55
+ возвращая тензор обратно на GPU (`cuda:0`).
56
+ """
57
+ f_mod = target_f if target_f is not None else F
58
+ t_mod = target_torch if target_torch is not None else torch
59
+ if f_mod is None or t_mod is None:
60
+ return False
61
+ if getattr(f_mod, "_work_miopen_wrapped", False):
62
+ return True
63
+ try:
64
+ t_mod.backends.cudnn.benchmark = False
65
+ except Exception:
66
+ pass
67
+
68
+ tensor_cls = getattr(t_mod, "Tensor", None)
69
+ f16_dt = getattr(t_mod, "float16", None)
70
+ f32_dt = getattr(t_mod, "float32", None)
71
+
72
+ def _to_cpu(val):
73
+ if tensor_cls is not None and isinstance(val, tensor_cls):
74
+ dt = f32_dt if (f16_dt is not None and val.dtype == f16_dt and f32_dt is not None) else val.dtype
75
+ return val.to(device="cpu", dtype=dt)
76
+ return val
77
+
78
+ def _wrap_conv(op_name):
79
+ orig_fn = getattr(f_mod, op_name, None)
80
+ if not callable(orig_fn):
81
+ return
82
+
83
+ def _safe_op(*args, **kwargs):
84
+ x = args[0] if args else kwargs.get("input")
85
+ is_cuda = bool(getattr(x, "is_cuda", False))
86
+ if not is_cuda:
87
+ return orig_fn(*args, **kwargs)
88
+ orig_dev = x.device
89
+ orig_dt = getattr(x, "dtype", None)
90
+ key = (op_name, str(orig_dt))
91
+ if key not in _MIOPEN_CPU_FALLBACK_OPS:
92
+ try:
93
+ return orig_fn(*args, **kwargs)
94
+ except Exception as e:
95
+ msg = str(e).lower()
96
+ if "miopen" not in msg and "cudnn" not in msg and "hip" not in msg:
97
+ raise
98
+ _MIOPEN_CPU_FALLBACK_OPS.add(key)
99
+ cpu_args = tuple(_to_cpu(a) for a in args)
100
+ cpu_kwargs = {k: _to_cpu(v) for k, v in kwargs.items()}
101
+ out = orig_fn(*cpu_args, **cpu_kwargs)
102
+ return out.to(device=orig_dev, dtype=orig_dt) if hasattr(out, "to") else out
103
+
104
+ try:
105
+ setattr(f_mod, op_name, _safe_op)
106
+ except Exception:
107
+ pass
108
+ try:
109
+ if hasattr(t_mod, op_name):
110
+ setattr(t_mod, op_name, _safe_op)
111
+ except Exception:
112
+ pass
113
+
114
+ for name in (
115
+ "conv1d",
116
+ "conv2d",
117
+ "conv3d",
118
+ "conv_transpose1d",
119
+ "conv_transpose2d",
120
+ "conv_transpose3d",
121
+ ):
122
+ _wrap_conv(name)
123
+ try:
124
+ f_mod._work_miopen_wrapped = True
125
+ except Exception:
126
+ pass
127
+ return True
128
+
129
+
130
+ if HAS_TORCH:
131
+ _install_rocm_miopen_fallback()
132
+
133
+
134
+ def _is_recoverable_gpu_error(exc):
135
+ msg = str(exc or "").lower()
136
+ return any(tok in msg for tok in (
137
+ "miopen",
138
+ "hip out of memory",
139
+ "cuda out of memory",
140
+ "out of memory",
141
+ "hiperror",
142
+ "cudnn",
143
+ "invalid device function",
144
+ ))
145
+
146
+
44
147
  def _inference_mode_dec():
45
148
  if HAS_TORCH and hasattr(torch, "inference_mode"):
46
149
  return torch.inference_mode()
@@ -127,39 +230,93 @@ class LocalCausalLM:
127
230
  self.rms_eps = float(self.cfg.get("rms_norm_eps", 1e-6))
128
231
  self.rope_theta = float(self.cfg.get("rope_theta", 1000000.0))
129
232
 
130
- self.embed_tokens = self.store.get("model.embed_tokens.weight")
131
- self.norm = self.store.get("model.norm.weight")
132
- self.lm_head = self.store.get("lm_head.weight")
133
- if self.lm_head is None:
134
- self.lm_head = self.embed_tokens
135
-
136
- self.compute_dtype = self.embed_tokens.dtype
137
-
138
- inv_freq = 1.0 / (
139
- self.rope_theta
140
- ** (torch.arange(0, self.head_dim, 2, dtype=torch.float32) / self.head_dim)
141
- )
142
- self.inv_freq = inv_freq
143
-
144
- self.layers = []
145
- for i in range(self.num_layers):
146
- p = f"model.layers.{i}"
147
- self.layers.append({
148
- "in_norm": self.store.get(f"{p}.input_layernorm.weight"),
149
- "q_proj": self.store.get(f"{p}.self_attn.q_proj.weight"),
150
- "q_bias": self.store.get(f"{p}.self_attn.q_proj.bias"),
151
- "k_proj": self.store.get(f"{p}.self_attn.k_proj.weight"),
152
- "k_bias": self.store.get(f"{p}.self_attn.k_proj.bias"),
153
- "v_proj": self.store.get(f"{p}.self_attn.v_proj.weight"),
154
- "v_bias": self.store.get(f"{p}.self_attn.v_proj.bias"),
155
- "o_proj": self.store.get(f"{p}.self_attn.o_proj.weight"),
156
- "q_norm": self.store.get(f"{p}.self_attn.q_norm.weight"),
157
- "k_norm": self.store.get(f"{p}.self_attn.k_norm.weight"),
158
- "post_norm": self.store.get(f"{p}.post_attention_layernorm.weight"),
159
- "gate_proj": self.store.get(f"{p}.mlp.gate_proj.weight"),
160
- "up_proj": self.store.get(f"{p}.mlp.up_proj.weight"),
161
- "down_proj": self.store.get(f"{p}.mlp.down_proj.weight"),
162
- })
233
+ target_dev, _ = _best_device_and_dtype()
234
+ self.device = target_dev
235
+
236
+ def _build_weights(dev):
237
+ embed_t = self.store.get("model.embed_tokens.weight")
238
+ norm_t = self.store.get("model.norm.weight")
239
+ lm_t = self.store.get("lm_head.weight")
240
+ if lm_t is None:
241
+ lm_t = embed_t
242
+ dt = embed_t.dtype if embed_t is not None else torch.bfloat16
243
+ if str(dev).startswith("cuda") and dt not in (torch.bfloat16, torch.float16, torch.float32):
244
+ dt = torch.bfloat16
245
+
246
+ def _move(t):
247
+ if t is None:
248
+ return None
249
+ if str(dev) == "cpu":
250
+ return t
251
+ return t.to(device=dev, dtype=dt)
252
+
253
+ embed_m = _move(embed_t)
254
+ norm_m = _move(norm_t)
255
+ lm_m = embed_m if (lm_t is embed_t) else _move(lm_t)
256
+ inv_f = (1.0 / (
257
+ self.rope_theta
258
+ ** (torch.arange(0, self.head_dim, 2, dtype=torch.float32) / self.head_dim)
259
+ )).to(device=dev)
260
+ layers_m = []
261
+ for i in range(self.num_layers):
262
+ p = f"model.layers.{i}"
263
+ layers_m.append({
264
+ "in_norm": _move(self.store.get(f"{p}.input_layernorm.weight")),
265
+ "q_proj": _move(self.store.get(f"{p}.self_attn.q_proj.weight")),
266
+ "q_bias": _move(self.store.get(f"{p}.self_attn.q_proj.bias")),
267
+ "k_proj": _move(self.store.get(f"{p}.self_attn.k_proj.weight")),
268
+ "k_bias": _move(self.store.get(f"{p}.self_attn.k_proj.bias")),
269
+ "v_proj": _move(self.store.get(f"{p}.self_attn.v_proj.weight")),
270
+ "v_bias": _move(self.store.get(f"{p}.self_attn.v_proj.bias")),
271
+ "o_proj": _move(self.store.get(f"{p}.self_attn.o_proj.weight")),
272
+ "q_norm": _move(self.store.get(f"{p}.self_attn.q_norm.weight")),
273
+ "k_norm": _move(self.store.get(f"{p}.self_attn.k_norm.weight")),
274
+ "post_norm": _move(self.store.get(f"{p}.post_attention_layernorm.weight")),
275
+ "gate_proj": _move(self.store.get(f"{p}.mlp.gate_proj.weight")),
276
+ "up_proj": _move(self.store.get(f"{p}.mlp.up_proj.weight")),
277
+ "down_proj": _move(self.store.get(f"{p}.mlp.down_proj.weight")),
278
+ })
279
+ return embed_m, norm_m, lm_m, dt, inv_f, layers_m
280
+
281
+ try:
282
+ (
283
+ self.embed_tokens,
284
+ self.norm,
285
+ self.lm_head,
286
+ self.compute_dtype,
287
+ self.inv_freq,
288
+ self.layers,
289
+ ) = _build_weights(self.device)
290
+ if str(self.device).startswith("cuda"):
291
+ # После переноса всех весов на GPU освобождаем CPU-mmap ссылки
292
+ self.store.tensors.clear()
293
+ for f_h, mm_h in self.store.files:
294
+ try:
295
+ mm_h.close()
296
+ except Exception:
297
+ pass
298
+ try:
299
+ f_h.close()
300
+ except Exception:
301
+ pass
302
+ self.store.files.clear()
303
+ except Exception:
304
+ if str(self.device).startswith("cuda"):
305
+ try:
306
+ torch.cuda.empty_cache()
307
+ except Exception:
308
+ pass
309
+ self.device = "cpu"
310
+ (
311
+ self.embed_tokens,
312
+ self.norm,
313
+ self.lm_head,
314
+ self.compute_dtype,
315
+ self.inv_freq,
316
+ self.layers,
317
+ ) = _build_weights("cpu")
318
+ else:
319
+ raise
163
320
 
164
321
  def _rope_cos_sin(self, positions, dtype):
165
322
  freqs = torch.outer(positions.to(torch.float32), self.inv_freq)
@@ -170,9 +327,11 @@ class LocalCausalLM:
170
327
 
171
328
  @_inference_mode_dec()
172
329
  def forward_step(self, input_ids, kv_cache, start_pos):
330
+ if input_ids.device != self.embed_tokens.device:
331
+ input_ids = input_ids.to(self.embed_tokens.device)
173
332
  seq_len = input_ids.shape[1]
174
333
  x = F.embedding(input_ids, self.embed_tokens) # [1, seq, hidden]
175
- positions = torch.arange(start_pos, start_pos + seq_len, dtype=torch.long)
334
+ positions = torch.arange(start_pos, start_pos + seq_len, dtype=torch.long, device=self.embed_tokens.device)
176
335
  cos, sin = self._rope_cos_sin(positions, self.compute_dtype)
177
336
 
178
337
  for idx, layer in enumerate(self.layers):
@@ -223,12 +382,13 @@ class LocalCausalLM:
223
382
  return logits[0]
224
383
 
225
384
  @_inference_mode_dec()
226
- def generate_stream(self, req_id, prompt_ids, max_new_tokens=384, temperature=0.6, top_p=0.9, repetition_penalty=1.08, eos_ids=None):
385
+ def generate_stream(self, req_id, prompt_ids, max_new_tokens=384, temperature=0.6, top_p=0.9, repetition_penalty=1.08, eos_ids=None, load_ms=0):
227
386
  eos_set = set(eos_ids or [151645, 151643])
228
387
  kv_cache = [None] * self.num_layers
229
388
  seen_tokens = list(prompt_ids)
389
+ dev = self.embed_tokens.device
230
390
 
231
- inp = torch.tensor([prompt_ids], dtype=torch.long)
391
+ inp = torch.tensor([prompt_ids], dtype=torch.long, device=dev)
232
392
  logits = self.forward_step(inp, kv_cache, 0)
233
393
  cur_pos = len(prompt_ids)
234
394
 
@@ -239,16 +399,22 @@ class LocalCausalLM:
239
399
  seen_tokens.append(next_token)
240
400
  print(json.dumps({"id": req_id, "event": "token", "token": next_token}), flush=True)
241
401
 
242
- inp_next = torch.tensor([[next_token]], dtype=torch.long)
402
+ inp_next = torch.tensor([[next_token]], dtype=torch.long, device=dev)
243
403
  logits = self.forward_step(inp_next, kv_cache, cur_pos)
244
404
  cur_pos += 1
245
405
 
246
- print(json.dumps({"id": req_id, "event": "done", "generated": cur_pos - len(prompt_ids)}), flush=True)
406
+ print(json.dumps({
407
+ "id": req_id,
408
+ "event": "done",
409
+ "generated": cur_pos - len(prompt_ids),
410
+ "device": _describe_torch_device(self.device),
411
+ "loadMs": int(load_ms or 0),
412
+ }), flush=True)
247
413
 
248
414
  def _sample(self, logits, seen_tokens, temperature, top_p, repetition_penalty):
249
415
  logits_f = logits.to(torch.float32).clone()
250
416
  if repetition_penalty and repetition_penalty != 1.0 and seen_tokens:
251
- uniq = torch.tensor(list(set(seen_tokens[-128:])), dtype=torch.long)
417
+ uniq = torch.tensor(list(set(seen_tokens[-128:])), dtype=torch.long, device=logits_f.device)
252
418
  vals = logits_f[uniq]
253
419
  logits_f[uniq] = torch.where(vals < 0, vals * repetition_penalty, vals / repetition_penalty)
254
420
 
@@ -648,9 +814,25 @@ def handle_image(req, cache):
648
814
  kwargs = {"prompt": prompt, "width": w, "height": h, "num_inference_steps": steps, "generator": gen}
649
815
  if is_turbo:
650
816
  kwargs["guidance_scale"] = 0.0
651
- with torch.inference_mode():
652
- out = pipe(**kwargs)
653
- img = out.images[0]
817
+ try:
818
+ with torch.inference_mode():
819
+ out = pipe(**kwargs)
820
+ img = out.images[0]
821
+ except Exception as e:
822
+ if str(device).startswith("cuda") and _is_recoverable_gpu_error(e):
823
+ try:
824
+ torch.cuda.empty_cache()
825
+ except Exception:
826
+ pass
827
+ device = "cpu"
828
+ pipe.to("cpu")
829
+ cache[("image", weights_dir)] = (pipe, "cpu")
830
+ kwargs["generator"] = torch.Generator(device="cpu").manual_seed(seed)
831
+ with torch.inference_mode():
832
+ out = pipe(**kwargs)
833
+ img = out.images[0]
834
+ else:
835
+ raise
654
836
  buf = io.BytesIO()
655
837
  img.save(buf, format="PNG")
656
838
  gen_ms = max(1, int((time.time() - t_gen0) * 1000))
@@ -995,6 +1177,71 @@ def _call_tts_gen(fn, max_new_tokens, **kwargs):
995
1177
  return fn(**kwargs)
996
1178
 
997
1179
 
1180
+ def _move_qwen_tts_vocoder_to_cpu(mdl):
1181
+ """Переносит декодер вокодера `speech_tokenizer` на CPU один раз при загрузке модели на GPU `cuda:0`.
1182
+
1183
+ Убирает сотни мелких перебросов `cuda:0 ↔ cpu` внутри `_install_rocm_miopen_fallback` для каждой
1184
+ отдельной Conv1d/ConvTranspose1d свёртки: коды 12 Гц кадров один раз уходят в Unified Memory на CPU
1185
+ и целиком декодируются в волну.
1186
+ """
1187
+ st = getattr(getattr(mdl, "model", None), "speech_tokenizer", None) or getattr(mdl, "speech_tokenizer", None)
1188
+ if st is None or getattr(st, "_work_cpu_vocoder_patched", False):
1189
+ return False
1190
+ inner = getattr(st, "model", None) or st
1191
+ decoder = getattr(inner, "decoder", None)
1192
+
1193
+ def _to_cpu_arg(v):
1194
+ if HAS_TORCH and torch is not None and isinstance(v, torch.Tensor):
1195
+ return v.detach().to("cpu")
1196
+ if isinstance(v, list):
1197
+ return [_to_cpu_arg(x) for x in v]
1198
+ if isinstance(v, tuple):
1199
+ return tuple(_to_cpu_arg(x) for x in v)
1200
+ if isinstance(v, dict):
1201
+ return {k: _to_cpu_arg(val) for k, val in v.items()}
1202
+ return v
1203
+
1204
+ if decoder is not None and callable(getattr(decoder, "forward", None)) and hasattr(decoder, "to"):
1205
+ try:
1206
+ cpu_dt = torch.float32 if (HAS_TORCH and torch is not None) else "float32"
1207
+ decoder.to(device="cpu", dtype=cpu_dt)
1208
+ orig_fwd = decoder.forward
1209
+
1210
+ def _cpu_decoder_fwd(*args, **kwargs):
1211
+ return orig_fwd(*(_to_cpu_arg(a) for a in args), **{k: _to_cpu_arg(v) for k, v in kwargs.items()})
1212
+
1213
+ decoder.forward = _cpu_decoder_fwd
1214
+ st._work_cpu_vocoder_patched = True
1215
+ return True
1216
+ except Exception:
1217
+ pass
1218
+
1219
+ dec = getattr(st, "decode", None)
1220
+ if not callable(dec):
1221
+ return False
1222
+ try:
1223
+ if hasattr(inner, "to"):
1224
+ cpu_dt = torch.float32 if (HAS_TORCH and torch is not None) else "float32"
1225
+ inner.to(device="cpu", dtype=cpu_dt)
1226
+ except Exception:
1227
+ return False
1228
+
1229
+ orig_dec = dec
1230
+
1231
+ def _cpu_decode(*args, **kwargs):
1232
+ return orig_dec(*(_to_cpu_arg(a) for a in args), **{k: _to_cpu_arg(v) for k, v in kwargs.items()})
1233
+
1234
+ try:
1235
+ st.decode = _cpu_decode
1236
+ orig_enc = getattr(st, "encode", None)
1237
+ if callable(orig_enc):
1238
+ st.encode = lambda *args, **kwargs: orig_enc(*(_to_cpu_arg(a) for a in args), **{k: _to_cpu_arg(v) for k, v in kwargs.items()})
1239
+ st._work_cpu_vocoder_patched = True
1240
+ return True
1241
+ except Exception:
1242
+ return False
1243
+
1244
+
998
1245
  def _load_qwen_tts_model(weights_dir):
999
1246
  from qwen_tts import Qwen3TTSModel
1000
1247
  device, dtype = _best_device_and_dtype()
@@ -1015,6 +1262,8 @@ def _load_qwen_tts_model(weights_dir):
1015
1262
  except Exception:
1016
1263
  mdl = Qwen3TTSModel.from_pretrained(weights_dir, device_map=dev, dtype=dt)
1017
1264
  _install_fast_qwen_tts_code_predictor(mdl)
1265
+ if str(dev).startswith("cuda"):
1266
+ _move_qwen_tts_vocoder_to_cpu(mdl)
1018
1267
  mdl._work_device = dev
1019
1268
  return mdl
1020
1269
  except Exception as e:
@@ -1235,9 +1484,155 @@ def handle_stt(req, cache):
1235
1484
  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}
1236
1485
 
1237
1486
 
1487
+ def _get_free_ram_gb():
1488
+ """Кроссплатформенно определить объём свободной оперативной памяти в ГБ."""
1489
+ try:
1490
+ if sys.platform == "win32":
1491
+ class _MEMORYSTATUSEX(ctypes.Structure):
1492
+ _fields_ = [
1493
+ ("dwLength", ctypes.c_ulong),
1494
+ ("dwMemoryLoad", ctypes.c_ulong),
1495
+ ("ullTotalPhys", ctypes.c_ulonglong),
1496
+ ("ullAvailPhys", ctypes.c_ulonglong),
1497
+ ("ullTotalPageFile", ctypes.c_ulonglong),
1498
+ ("ullAvailPageFile", ctypes.c_ulonglong),
1499
+ ("ullTotalVirtual", ctypes.c_ulonglong),
1500
+ ("ullAvailVirtual", ctypes.c_ulonglong),
1501
+ ("ullAvailExtendedVirtual", ctypes.c_ulonglong),
1502
+ ]
1503
+ st = _MEMORYSTATUSEX()
1504
+ st.dwLength = ctypes.sizeof(_MEMORYSTATUSEX)
1505
+ if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(st)):
1506
+ return float(st.ullAvailPhys) / (1024.0 ** 3)
1507
+ elif os.path.isfile("/proc/meminfo"):
1508
+ with open("/proc/meminfo", "r", encoding="utf-8") as f:
1509
+ for line in f:
1510
+ if line.startswith("MemAvailable:"):
1511
+ kb = float(line.split()[1])
1512
+ return kb / (1024.0 ** 2)
1513
+ except Exception:
1514
+ pass
1515
+ return None
1516
+
1517
+
1518
+ def _release_cached_item(obj):
1519
+ try:
1520
+ if isinstance(obj, tuple) and len(obj) >= 1 and hasattr(obj[0], "to"):
1521
+ try:
1522
+ obj[0].to("cpu")
1523
+ except Exception:
1524
+ pass
1525
+ elif hasattr(obj, "to"):
1526
+ try:
1527
+ obj.to("cpu")
1528
+ except Exception:
1529
+ pass
1530
+ except Exception:
1531
+ pass
1532
+
1533
+
1534
+ def _evict_memory_if_needed(
1535
+ mod_cache,
1536
+ mod_last_used,
1537
+ models,
1538
+ llm_last_used,
1539
+ cache_lock=None,
1540
+ keep_mod_key=None,
1541
+ keep_llm_key=None,
1542
+ now_ts=None,
1543
+ ):
1544
+ """Умная очистка памяти:
1545
+ - Тяжёлую диффузию (`image`, напр. Z-Image-Turbo) выгружаем через `WORK_IMAGE_IDLE_SEC` (10 мин)
1546
+ или при падении свободной RAM ниже `WORK_MIN_FREE_RAM_GB` (20 ГБ).
1547
+ - Лёгкие модели (embed, rerank, tts, stt, 0.6B/4B) держим постоянно горячими,
1548
+ выгружая по LRU только при критической нехватке RAM (`< WORK_CRIT_FREE_RAM_GB`, 10 ГБ).
1549
+ """
1550
+ now = float(now_ts if now_ts is not None else time.time())
1551
+ image_idle_sec = float(os.environ.get("WORK_IMAGE_IDLE_SEC", "600"))
1552
+ min_free_gb = float(os.environ.get("WORK_MIN_FREE_RAM_GB", "20"))
1553
+ crit_free_gb = float(os.environ.get("WORK_CRIT_FREE_RAM_GB", "10"))
1554
+ free_gb = _get_free_ram_gb()
1555
+ evicted = []
1556
+
1557
+ def _do():
1558
+ low_mem = free_gb is not None and free_gb < min_free_gb
1559
+ for k in list(mod_cache.keys()):
1560
+ if not (isinstance(k, tuple) and len(k) >= 1 and k[0] == "image"):
1561
+ continue
1562
+ if k == keep_mod_key:
1563
+ continue
1564
+ idle = now - float(mod_last_used.get(k, now))
1565
+ if idle >= image_idle_sec or low_mem:
1566
+ obj = mod_cache.pop(k, None)
1567
+ mod_last_used.pop(k, None)
1568
+ _release_cached_item(obj)
1569
+ evicted.append(k)
1570
+
1571
+ if free_gb is not None and free_gb < crit_free_gb:
1572
+ # Критическая нехватка памяти — выгружаем самую давно неиспользуемую неактивную модель
1573
+ candidates = []
1574
+ for k in list(mod_cache.keys()):
1575
+ if k != keep_mod_key:
1576
+ candidates.append(("mod", k, float(mod_last_used.get(k, 0.0))))
1577
+ for k in list(models.keys()):
1578
+ if k != keep_llm_key:
1579
+ candidates.append(("llm", k, float(llm_last_used.get(k, 0.0))))
1580
+ candidates.sort(key=lambda item: item[2])
1581
+ for kind, k, _ in candidates[:2]:
1582
+ if kind == "mod":
1583
+ obj = mod_cache.pop(k, None)
1584
+ mod_last_used.pop(k, None)
1585
+ _release_cached_item(obj)
1586
+ evicted.append(k)
1587
+ else:
1588
+ obj = models.pop(k, None)
1589
+ llm_last_used.pop(k, None)
1590
+ _release_cached_item(obj)
1591
+ evicted.append(("llm", k))
1592
+
1593
+ if cache_lock is not None:
1594
+ with cache_lock:
1595
+ _do()
1596
+ else:
1597
+ _do()
1598
+
1599
+ if evicted:
1600
+ try:
1601
+ gc.collect()
1602
+ except Exception:
1603
+ pass
1604
+ if HAS_TORCH and torch is not None and torch.cuda.is_available():
1605
+ try:
1606
+ torch.cuda.empty_cache()
1607
+ except Exception:
1608
+ pass
1609
+ return evicted
1610
+
1611
+
1238
1612
  def main():
1239
1613
  models = {}
1240
1614
  mod_cache = {}
1615
+ mod_last_used = {}
1616
+ llm_last_used = {}
1617
+ cache_lock = threading.Lock()
1618
+ idle_timers = {"image": None}
1619
+
1620
+ def _schedule_image_idle_eviction():
1621
+ try:
1622
+ prev = idle_timers.get("image")
1623
+ if prev is not None:
1624
+ prev.cancel()
1625
+ delay = max(5.0, float(os.environ.get("WORK_IMAGE_IDLE_SEC", "600")) + 1.0)
1626
+ t = threading.Timer(
1627
+ delay,
1628
+ lambda: _evict_memory_if_needed(mod_cache, mod_last_used, models, llm_last_used, cache_lock=cache_lock),
1629
+ )
1630
+ t.daemon = True
1631
+ t.start()
1632
+ idle_timers["image"] = t
1633
+ except Exception:
1634
+ pass
1635
+
1241
1636
  print(json.dumps({"event": "ready"}), flush=True)
1242
1637
 
1243
1638
  for line in sys.stdin:
@@ -1272,6 +1667,11 @@ def main():
1272
1667
  continue
1273
1668
  if op in ("embed", "rerank", "image", "tts", "stt"):
1274
1669
  t0 = time.time()
1670
+ mod_key = (op, str(req.get("weightsDir") or ""))
1671
+ _evict_memory_if_needed(
1672
+ mod_cache, mod_last_used, models, llm_last_used,
1673
+ cache_lock=cache_lock, keep_mod_key=mod_key,
1674
+ )
1275
1675
  fn = {
1276
1676
  "embed": handle_embed,
1277
1677
  "rerank": handle_rerank,
@@ -1279,7 +1679,11 @@ def main():
1279
1679
  "tts": handle_tts,
1280
1680
  "stt": handle_stt,
1281
1681
  }[op]
1282
- res = fn(req, mod_cache)
1682
+ with cache_lock:
1683
+ res = fn(req, mod_cache)
1684
+ mod_last_used[mod_key] = time.time()
1685
+ if op == "image":
1686
+ _schedule_image_idle_eviction()
1283
1687
  if "durationMs" not in res:
1284
1688
  res["durationMs"] = int((time.time() - t0) * 1000)
1285
1689
  print(json.dumps({"id": req_id, "event": "result", "data": res}), flush=True)
@@ -1291,15 +1695,26 @@ def main():
1291
1695
  temperature = float(req.get("temperature", 0.6))
1292
1696
  eos_ids = req.get("eosTokenIds", [151645, 151643])
1293
1697
 
1294
- if weights_dir not in models:
1295
- models[weights_dir] = LocalCausalLM(weights_dir)
1296
-
1297
- models[weights_dir].generate_stream(
1698
+ _evict_memory_if_needed(
1699
+ mod_cache, mod_last_used, models, llm_last_used,
1700
+ cache_lock=cache_lock, keep_llm_key=weights_dir,
1701
+ )
1702
+ load_ms = 0
1703
+ with cache_lock:
1704
+ if weights_dir not in models:
1705
+ t_l0 = time.time()
1706
+ models[weights_dir] = LocalCausalLM(weights_dir)
1707
+ load_ms = int((time.time() - t_l0) * 1000)
1708
+ llm_last_used[weights_dir] = time.time()
1709
+ mdl_ref = models[weights_dir]
1710
+
1711
+ mdl_ref.generate_stream(
1298
1712
  req_id=req_id,
1299
1713
  prompt_ids=prompt_ids,
1300
1714
  max_new_tokens=max_new_tokens,
1301
1715
  temperature=temperature,
1302
1716
  eos_ids=eos_ids,
1717
+ load_ms=load_ms,
1303
1718
  )
1304
1719
  except Exception as e:
1305
1720
  err_str = str(e)