MogensR commited on
Commit
2c9ad3e
·
1 Parent(s): 05c8f4b

Update models/loaders/matanyone_loader.py

Browse files
Files changed (1) hide show
  1. models/loaders/matanyone_loader.py +246 -671
models/loaders/matanyone_loader.py CHANGED
@@ -1,711 +1,286 @@
1
  #!/usr/bin/env python3
2
  # -*- coding: utf-8 -*-
3
  """
4
- MatAnyone Loader + Stateful Adapter (Fixed Tensor Shapes, OOM-resilient)
5
- =======================================================================
6
-
7
- CHAPTERS
8
- 1) Overview & Rationale
9
- 2) Imports & Logger
10
- 3) EasyDict Polyfill
11
- 4) Tensor Utilities (device, shape, resize, padding)
12
- 5) Precision Selection (fp16/bf16/fp32)
13
- 6) Stateful Session (_MatAnyoneSession) ← FIX: CHW / 1HW only (no temporal axis)
14
- 7) Loader (MatAnyoneLoader)
15
- 8) Public Symbols
16
- 9) CLI Demo (optional quick test)
17
-
18
- Key Fix vs. previous version
19
- ----------------------------
20
- - Removed the extra “temporal” axis that produced 5D tensors like [1,1,3,H,W].
21
- - MatAnyone now receives:
22
- • Image: CHW (float, in [0,1]) — or internally BCHW collapsed to CHW.
23
- • Mask : 1HW (float, in [0,1]) on the first frame only; later frames mask=None.
24
- - Kept: downscale ladder, padding to multiple of 16, mixed precision, long-term memory config.
25
  """
26
 
27
- # ============================================================================
28
- # 2) IMPORTS & LOGGER
29
- # ============================================================================
30
- from __future__ import annotations
31
  import os
32
  import time
33
  import logging
 
34
  import traceback
35
- from typing import Optional, Dict, Any, Tuple, List
 
36
 
37
  import numpy as np
38
  import torch
39
- import torch.nn.functional as F
40
- import inspect
41
- import threading
42
- import contextlib
43
 
44
  logger = logging.getLogger(__name__)
45
 
46
 
47
- # ============================================================================
48
- # 3) EASYDICT POLYFILL
49
- # ============================================================================
50
- class EasyDict(dict):
51
- """Recursive dict with dot access."""
52
- def __init__(self, d=None, **kwargs):
53
- if d is None:
54
- d = {}
55
- if kwargs:
56
- d.update(**kwargs)
57
- for k, v in d.items():
58
- if isinstance(v, dict):
59
- self[k] = EasyDict(v)
60
- elif isinstance(v, list):
61
- self[k] = [EasyDict(i) if isinstance(i, dict) else i for i in v]
62
- else:
63
- self[k] = v
64
-
65
- def __getattr__(self, name): # dot-get
66
- try:
67
- return self[name]
68
- except KeyError:
69
- raise AttributeError(name)
70
-
71
- def __setattr__(self, name, value): # dot-set
72
- self[name] = value
73
-
74
- def __delattr__(self, name): # dot-del
75
- del self[name]
76
-
77
-
78
- # ============================================================================
79
- # 4) TENSOR UTILITIES (DEVICE, SHAPE, RESIZE, PADDING)
80
- # ============================================================================
81
- def _select_device(pref: str) -> str:
82
- pref = (pref or "").lower()
83
- if pref.startswith("cuda"):
84
- return "cuda" if torch.cuda.is_available() else "cpu"
85
- if pref == "cpu":
86
- return "cpu"
87
- return "cuda" if torch.cuda.is_available() else "cpu"
88
-
89
-
90
- def _as_tensor_on_device(x, device: str) -> torch.Tensor:
91
- if isinstance(x, torch.Tensor):
92
- return x.to(device, non_blocking=True)
93
- return torch.from_numpy(np.asarray(x)).to(device, non_blocking=True)
94
-
95
-
96
- def _to_bchw(x, device: str, is_mask: bool = False) -> torch.Tensor:
97
- """
98
- Normalize input to BCHW (image) or B1HW (mask).
99
- Accepts: HWC, CHW, BCHW, BHWC, (accidental) 5D, and HW.
100
- Defensive against dtype/range; output is clamped to [0,1].
101
- """
102
- x = _as_tensor_on_device(x, device)
103
- if x.dtype == torch.uint8:
104
- x = x.float().div_(255.0)
105
- elif x.dtype in (torch.int16, torch.int32, torch.int64):
106
- x = x.float()
107
-
108
- # If upstream passed a 5D tensor (e.g., (B,1,C,H,W) or (B,T,C,H,W)), squeeze a singleton middle axis.
109
- if x.ndim == 5:
110
- # Prefer to squeeze the 2nd dim if it's 1; otherwise take the first slice.
111
- if x.shape[1] == 1:
112
- x = x.squeeze(1) # -> BCHW
113
- else:
114
- x = x[:, 0, ...] # -> BCHW
115
-
116
- if x.ndim == 4:
117
- # Handle BHWC → BCHW
118
- if x.shape[-1] in (1, 3, 4) and x.shape[1] not in (1, 3, 4):
119
- x = x.permute(0, 3, 1, 2).contiguous()
120
- elif x.ndim == 3:
121
- # HWC → CHW
122
- if x.shape[-1] in (1, 3, 4):
123
- x = x.permute(2, 0, 1).contiguous()
124
- # CHW → BCHW
125
- x = x.unsqueeze(0)
126
- elif x.ndim == 2:
127
- # HW → B1HW (mask) or B3HW (image)
128
- x = x.unsqueeze(0).unsqueeze(0)
129
- if not is_mask:
130
- x = x.repeat(1, 3, 1, 1)
131
- else:
132
- raise ValueError(f"_to_bchw: unsupported ndim={x.ndim}")
133
-
134
- if is_mask:
135
- # Ensure single-channel B1HW, clamped and float32
136
- if x.shape[1] > 1:
137
- x = x[:, :1]
138
- x = x.clamp_(0.0, 1.0).to(torch.float32)
139
- else:
140
- # Ensure RGB
141
- if x.shape[1] == 4:
142
- x = x[:, :3, ...]
143
- elif x.shape[1] == 1:
144
- x = x.repeat(1, 3, 1, 1)
145
- x = x.clamp_(0.0, 1.0)
146
-
147
- return x.contiguous()
148
-
149
-
150
- def _to_chw_image(img_bchw: torch.Tensor) -> torch.Tensor:
151
- """BCHW → CHW (take batch 0 if present)."""
152
- if img_bchw.ndim == 4 and img_bchw.shape[0] == 1:
153
- return img_bchw[0]
154
- if img_bchw.ndim == 3:
155
- return img_bchw
156
- raise ValueError(f"_to_chw_image: expected BCHW or CHW, got {tuple(img_bchw.shape)}")
157
-
158
-
159
- def _to_1hw_mask(msk_b1hw: torch.Tensor) -> torch.Tensor:
160
- """B1HW → 1HW (drop batch)."""
161
- if msk_b1hw is None:
162
- raise ValueError("_to_1hw_mask: mask is None")
163
- if msk_b1hw.ndim == 4 and msk_b1hw.shape[1] == 1:
164
- return msk_b1hw[0] # 1HW
165
- if msk_b1hw.ndim == 3 and msk_b1hw.shape[0] == 1:
166
- return msk_b1hw
167
- raise ValueError(f"_to_1hw_mask: expected B1HW or 1HW, got {tuple(msk_b1hw.shape)}")
168
-
169
-
170
- def _resize_bchw(x: Optional[torch.Tensor], size_hw: Tuple[int, int], is_mask: bool = False) -> Optional[torch.Tensor]:
171
- """Resize BCHW or B1HW to (H, W) using bilinear (image) or nearest (mask)."""
172
- if x is None:
173
- return None
174
- if x.shape[-2:] == size_hw:
175
- return x
176
- mode = "nearest" if is_mask else "bilinear"
177
- return F.interpolate(x, size_hw, mode=mode, align_corners=False if mode == "bilinear" else None)
178
-
179
-
180
- def _to_b1hw_alpha(alpha, device: str) -> torch.Tensor:
181
- """Convert arbitrary mask-like input to B1HW float32 [0,1]."""
182
- t = torch.as_tensor(alpha, device=device).float()
183
- # Squeeze extra dims down to HW/1HW first
184
- while t.ndim > 4:
185
- t = t.squeeze(0)
186
- if t.ndim == 4:
187
- # Expecting BxCxHxW; force B=1, C=1
188
- if t.shape[0] != 1:
189
- t = t[:1]
190
- if t.shape[1] != 1:
191
- t = t[:, :1]
192
- elif t.ndim == 3:
193
- # Could be CxHxW or HxWx1
194
- if t.shape[0] == 1:
195
- t = t.unsqueeze(0) # 1x1xHxW
196
- elif t.shape[-1] == 1:
197
- t = t.permute(2, 0, 1).unsqueeze(0) # 1x1xHxW
198
- else:
199
- # If C>1, take first channel
200
- t = t[:1, ...].unsqueeze(0)
201
- elif t.ndim == 2:
202
- t = t.unsqueeze(0).unsqueeze(0)
203
- else:
204
- raise ValueError(f"_to_b1hw_alpha: unsupported ndim={t.ndim}")
205
- t = t.clamp_(0.0, 1.0).contiguous()
206
- return t
207
-
208
-
209
- def _to_2d_alpha_numpy(x) -> np.ndarray:
210
- """Convert any mask-like tensor to 2D float32 numpy [H,W] in [0,1]."""
211
- t = torch.as_tensor(x).float()
212
- # Squeeze down to 2D
213
- while t.ndim > 2:
214
- if t.ndim == 4 and t.shape[0] == 1 and t.shape[1] == 1:
215
- t = t[0, 0]
216
- elif t.ndim == 3 and t.shape[0] == 1:
217
- t = t[0]
218
- else:
219
- t = t.squeeze(0)
220
- t = t.clamp_(0.0, 1.0)
221
- out = t.detach().cpu().numpy().astype(np.float32)
222
- return np.ascontiguousarray(out)
223
-
224
-
225
- def _compute_scaled_size(h: int, w: int, max_edge: int, target_pixels: int) -> Tuple[int, int, float]:
226
- """Compute a safe scaled size that respects a max edge and total pixels."""
227
- if h <= 0 or w <= 0:
228
- return h, w, 1.0
229
- s1 = min(1.0, float(max_edge) / float(max(h, w))) if max_edge > 0 else 1.0
230
- s2 = min(1.0, (float(target_pixels) / float(h * w)) ** 0.5) if target_pixels > 0 else 1.0
231
- s = min(s1, s2)
232
- nh = max(128, int(round(h * s))) # minimum of 128 to avoid very small feature maps
233
- nw = max(128, int(round(w * s)))
234
- return nh, nw, s
235
-
236
-
237
- def _pad_to_multiple_3d(t: torch.Tensor, multiple: int = 16) -> torch.Tensor:
238
- """
239
- Pad a 3D tensor (C,H,W) to multiples of `multiple`. Works for CHW and 1HW.
240
- Returns a tensor with same ndim.
241
- """
242
- if t.ndim != 3:
243
- raise ValueError(f"_pad_to_multiple_3d: expected 3D, got {t.ndim}D")
244
- c, h, w = t.shape
245
- pad_h = (multiple - h % multiple) % multiple
246
- pad_w = (multiple - w % multiple) % multiple
247
- if pad_h or pad_w:
248
- t = F.pad(t, (0, pad_w, 0, pad_h)) # (left,right,top,bottom)
249
- return t
250
-
251
-
252
- def debug_shapes(tag: str, image, mask) -> None:
253
- """Log shapes/dtypes/min/max for quick inspection."""
254
- def _info(name, v):
255
- try:
256
- tv = torch.as_tensor(v)
257
- mn = float(tv.min()) if tv.numel() else float("nan")
258
- mx = float(tv.max()) if tv.numel() else float("nan")
259
- logger.info(f"[{tag}:{name}] shape={tuple(tv.shape)} dtype={tv.dtype} min={mn:.4f} max={mx:.4f}")
260
- except Exception as e:
261
- logger.info(f"[{tag}:{name}] type={type(v)} err={e}")
262
- _info("image", image)
263
- _info("mask", mask)
264
-
265
-
266
- # ============================================================================
267
- # 5) PRECISION SELECTION (fp16/bf16/fp32)
268
- # ============================================================================
269
- def _choose_precision(device: str) -> Tuple[torch.dtype, bool, Optional[torch.dtype]]:
270
- """
271
- Pick model weights dtype and autocast dtype (fp16>bf16>fp32), preferring fp16 for T4.
272
- Returns: (model_dtype, use_autocast, autocast_dtype)
273
- """
274
- if device != "cuda":
275
- return torch.float32, False, None
276
- cc = torch.cuda.get_device_capability() if torch.cuda.is_available() else (0, 0)
277
- fp16_ok = cc[0] >= 7 # Volta+
278
- bf16_ok = (cc[0] >= 8) and hasattr(torch.cuda, "is_bf16_supported") and torch.cuda.is_bf16_supported()
279
- if fp16_ok:
280
- return torch.float16, True, torch.float16 # T4 prefers fp16
281
- if bf16_ok:
282
- return torch.bfloat16, True, torch.bfloat16
283
- return torch.float32, False, None
284
-
285
-
286
- # ============================================================================
287
- # 6) STATEFUL SESSION (NO TEMPORAL AXIS; STRICT CHW/1HW)
288
- # ============================================================================
289
- class _MatAnyoneSession:
290
- """
291
- Stateful controller around InferenceCore with OOM-resilient inference.
292
- First call MUST supply a coarse mask (we enforce 1HW internally).
293
- Subsequent calls should pass mask=None (temporal propagation handled by core).
294
- """
295
- def __init__(
296
- self,
297
- core,
298
- device: str,
299
- model_dtype: torch.dtype,
300
- use_autocast: bool,
301
- autocast_dtype: Optional[torch.dtype],
302
- max_edge: int = 768,
303
- target_pixels: int = 600_000, # ~775x775 by area
304
- ):
305
- self.core = core
306
- self.device = device
307
- self.model_dtype = model_dtype
308
- self.use_autocast = use_autocast and (device == "cuda")
309
- self.autocast_dtype = autocast_dtype if self.use_autocast else None
310
- self.max_edge = int(max_edge)
311
- self.target_pixels = int(target_pixels)
312
- self.started = False
313
- self._lock = threading.Lock()
314
-
315
- # Introspect optional API surfaces
316
- try:
317
- sig = inspect.signature(self.core.step)
318
- self._has_first_frame_pred = "first_frame_pred" in sig.parameters
319
- except Exception:
320
- self._has_first_frame_pred = True
321
- self._has_prob_to_mask = hasattr(self.core, "output_prob_to_mask")
322
-
323
- def reset(self):
324
- with self._lock:
325
- try:
326
- if hasattr(self.core, "clear_memory"):
327
- self.core.clear_memory()
328
- except Exception:
329
- pass
330
- self.started = False
331
-
332
- def _scaled_ladder(self, H: int, W: int) -> List[Tuple[int, int]]:
333
- """
334
- Build a list of decreasing (H,W) resolutions to attempt to avoid OOM.
335
- """
336
- nh, nw, s = _compute_scaled_size(H, W, self.max_edge, self.target_pixels)
337
- sizes = [(nh, nw)]
338
- if s < 1.0:
339
- f_chain = (0.85, 0.70, 0.55, 0.40)
340
- cur_h, cur_w = nh, nw
341
- for f in f_chain:
342
- cur_h = max(128, int(cur_h * f))
343
- cur_w = max(128, int(cur_w * f))
344
- if sizes[-1] != (cur_h, cur_w):
345
- sizes.append((cur_h, cur_w))
346
- return sizes
347
-
348
- def _to_alpha(self, out_prob):
349
- """Convert model output probabilities to a matte."""
350
- if self._has_prob_to_mask:
351
- try:
352
- return self.core.output_prob_to_mask(out_prob, matting=True)
353
- except Exception:
354
- pass
355
- t = torch.as_tensor(out_prob).float()
356
- if t.ndim == 4: # BxCxHxW
357
- return t[0, 0] if t.shape[1] >= 1 else t[0].mean(0)
358
- if t.ndim == 3: # CxHxW
359
- return t[0] if t.shape[0] >= 1 else t.mean(0)
360
- return t
361
-
362
- def __call__(self, image, mask=None, **kwargs) -> np.ndarray:
363
- """
364
- Returns a 2-D float32 alpha [H,W].
365
- - frame 0: provide coarse mask → session initialized
366
- - frames 1..N: pass mask=None (propagation)
367
- """
368
- with self._lock:
369
- # ---- 1) Normalize inputs to BCHW (image) and B1HW (mask), then collapse to CHW / 1HW
370
- img_bchw = _to_bchw(image, self.device, is_mask=False) # BCHW
371
- H, W = img_bchw.shape[-2], img_bchw.shape[-1]
372
- img_bchw = img_bchw.to(self.model_dtype, non_blocking=True)
373
- msk_b1hw = _to_bchw(mask, self.device, is_mask=True) if mask is not None else None
374
- if msk_b1hw is not None and msk_b1hw.shape[-2:] != (H, W):
375
- msk_b1hw = _resize_bchw(msk_b1hw, (H, W), is_mask=True)
376
-
377
- img_chw = _to_chw_image(img_bchw) # CHW
378
- mask_1hw = _to_1hw_mask(msk_b1hw) if msk_b1hw is not None else None # 1HW or None
379
-
380
- # ---- 2) Downscale ladder to avoid OOM
381
- sizes = self._scaled_ladder(H, W)
382
- last_exc = None
383
-
384
- for (th, tw) in sizes:
385
- try:
386
- # 2a) Resize image (bilinear) and mask (nearest) to ladder size
387
- if (th, tw) == (H, W):
388
- img_in = img_chw
389
- msk_in = mask_1hw
390
- else:
391
- img_in = F.interpolate(img_chw.unsqueeze(0), size=(th, tw),
392
- mode="bilinear", align_corners=False)[0] # CHW
393
- msk_in = None
394
- if mask_1hw is not None:
395
- msk_in = F.interpolate(mask_1hw.unsqueeze(0), size=(th, tw),
396
- mode="nearest")[0] # 1HW
397
-
398
- # 2b) Pad to multiple of 16 (per-model stability)
399
- img_in = _pad_to_multiple_3d(img_in) # CHW
400
- if msk_in is not None:
401
- msk_in = _pad_to_multiple_3d(msk_in) # 1HW
402
-
403
- # ---- 3) Forward pass (STRICT CHW / 1HW; NO TEMPORAL AXIS)
404
- with torch.inference_mode():
405
- amp_ctx = (
406
- torch.autocast(device_type="cuda", dtype=self.autocast_dtype)
407
- if self.use_autocast else
408
- contextlib.nullcontext()
409
- )
410
- with amp_ctx:
411
- if not self.started:
412
- if msk_in is None:
413
- logger.warning("First frame arrived without a mask; returning neutral alpha.")
414
- return np.full((H, W), 0.5, dtype=np.float32)
415
-
416
- # Initialize with first frame (explicit mask)
417
- _ = self.core.step(image=img_in, mask=msk_in) # ← CHW + 1HW
418
- if self._has_first_frame_pred:
419
- out_prob = self.core.step(image=img_in, first_frame_pred=True)
420
- else:
421
- out_prob = self.core.step(image=img_in)
422
- self.started = True
423
- else:
424
- # Subsequent frames; core uses memory internally
425
- out_prob = self.core.step(image=img_in) # ← CHW
426
-
427
- # ---- 4) Convert to alpha + unpad/upsample back to full res if needed
428
- alpha = self._to_alpha(out_prob)
429
- if alpha.ndim >= 2:
430
- alpha = alpha[..., :th, :tw] # remove pad
431
-
432
- if (th, tw) != (H, W):
433
- a_b1hw = _to_b1hw_alpha(alpha, device=img_bchw.device)
434
- a_b1hw = F.interpolate(a_b1hw, size=(H, W), mode="bilinear", align_corners=False)
435
- alpha = a_b1hw[0, 0]
436
-
437
- return _to_2d_alpha_numpy(alpha)
438
-
439
- except torch.cuda.OutOfMemoryError as e:
440
- last_exc = e
441
- torch.cuda.empty_cache()
442
- logger.warning(f"MatAnyone OOM at {th}x{tw}; retrying smaller. {e}")
443
- continue
444
- except Exception as e:
445
- last_exc = e
446
- torch.cuda.empty_cache()
447
- logger.debug(traceback.format_exc())
448
- logger.warning(f"MatAnyone call failed at {th}x{tw}; retrying smaller. {e}")
449
- continue
450
-
451
- # ---- 5) All attempts failed – return input mask or neutral alpha
452
- logger.warning(f"MatAnyone calls failed; returning input mask or neutral alpha. {last_exc}")
453
- if mask_1hw is not None:
454
- return _to_2d_alpha_numpy(mask_1hw)
455
- return np.full((H, W), 0.5, dtype=np.float32)
456
-
457
-
458
- # ============================================================================
459
- # 7) LOADER (MatAnyoneLoader)
460
- # ============================================================================
461
  class MatAnyoneLoader:
462
  """
463
- Official MatAnyone loader with stateful, OOM-resilient session adapter.
 
 
464
  """
 
465
  def __init__(self, device: str = "cuda", cache_dir: str = "./checkpoints/matanyone_cache"):
466
- self.device = _select_device(device)
467
  self.cache_dir = cache_dir
468
  os.makedirs(self.cache_dir, exist_ok=True)
469
- self.model = None
470
- self.core = None
471
- self.adapter = None
472
  self.model_id = "PeiqingYang/MatAnyone"
473
  self.load_time = 0.0
474
-
475
- # --- Robust imports (works with different packaging layouts) ---
476
- def _import_model_and_core(self):
477
- model_cls = core_cls = None
478
- err_msgs = []
479
- for mod, cls in [
480
- ("matanyone.model.matanyone", "MatAnyone"),
481
- ("matanyone", "MatAnyone"),
482
- ]:
483
- try:
484
- m = __import__(mod, fromlist=[cls])
485
- model_cls = getattr(m, cls)
486
- break
487
- except Exception as e:
488
- err_msgs.append(f"model {mod}.{cls}: {e}")
489
- for mod, cls in [
490
- ("matanyone.inference.inference_core", "InferenceCore"),
491
- ("matanyone", "InferenceCore"),
492
- ]:
493
- try:
494
- m = __import__(mod, fromlist=[cls])
495
- core_cls = getattr(m, cls)
496
- break
497
- except Exception as e:
498
- err_msgs.append(f"core {mod}.{cls}: {e}")
499
- if model_cls is None or core_cls is None:
500
- raise ImportError("Could not import MatAnyone / InferenceCore: " + " | ".join(err_msgs))
501
- return model_cls, core_cls
502
-
503
- def load(self) -> Optional[Any]:
504
  logger.info(f"Loading MatAnyone from HF: {self.model_id} (device={self.device})")
505
  t0 = time.time()
 
506
  try:
507
- model_cls, core_cls = self._import_model_and_core()
508
- model_dtype, use_autocast, autocast_dtype = _choose_precision(self.device)
509
- logger.info(f"MatAnyone precision: weights={model_dtype}, autocast={use_autocast and autocast_dtype}")
510
-
511
- # HF weights (safetensors)
512
- self.model = model_cls.from_pretrained(self.model_id)
513
-
514
- # Move to device + dtype when possible
515
- try:
516
- self.model = self.model.to(self.device).to(model_dtype)
517
- except Exception:
518
- self.model = self.model.to(self.device)
519
- self.model.eval()
520
-
521
- # Full default cfg from official config.json (kept; enables memory features)
522
- default_cfg = {
523
- "amp": False,
524
- "chunk_size": 1, # single-frame stepping
525
- "flip_aug": False,
526
- "long_term": {
527
- "buffer_tokens": 2000,
528
- "count_usage": True,
529
- "max_mem_frames": 10,
530
- "max_num_tokens": 10000,
531
- "min_mem_frames": 5,
532
- "num_prototypes": 128
533
- },
534
- "max_internal_size": -1,
535
- "max_mem_frames": 5,
536
- "mem_every": 5,
537
- "model": {
538
- "aux_loss": {"query": {"enabled": True, "weight": 0.01},
539
- "sensory": {"enabled": True, "weight": 0.01}},
540
- "embed_dim": 256,
541
- "key_dim": 64,
542
- "mask_decoder": {"up_dims": [256, 128, 128, 64, 16]},
543
- "mask_encoder": {"final_dim": 256, "type": "resnet18"},
544
- "object_summarizer": {"add_pe": True, "embed_dim": 256, "num_summaries": 16},
545
- "object_transformer": {
546
- "embed_dim": 256, "ff_dim": 2048, "num_blocks": 3, "num_heads": 8,
547
- "num_queries": 16,
548
- "pixel_self_attention": {"add_pe_to_qkv": [True, True, False]},
549
- "query_self_attention": {"add_pe_to_qkv": [True, True, False]},
550
- "read_from_memory": {"add_pe_to_qkv": [True, True, False]},
551
- "read_from_past": {"add_pe_to_qkv": [True, True, False]},
552
- "read_from_pixel": {"add_pe_to_qkv": [True, True, False], "input_add_pe": False, "input_norm": False},
553
- "read_from_query": {"add_pe_to_qkv": [True, True, False], "output_norm": False}
554
- },
555
- "pixel_dim": 256,
556
- "pixel_encoder": {"ms_dims": [1024, 512, 256, 64, 3], "type": "resnet50"},
557
- "pixel_mean": [0.485, 0.456, 0.406],
558
- "pixel_pe_scale": 32,
559
- "pixel_pe_temperature": 128,
560
- "pixel_std": [0.229, 0.224, 0.225],
561
- "pretrained_resnet": False,
562
- "sensory_dim": 256,
563
- "value_dim": 256
564
- },
565
- "output_dir": None,
566
- "save_all": True,
567
- "save_aux": False,
568
- "save_scores": False,
569
- "stagger_updates": 5,
570
- "top_k": 30,
571
- "use_all_masks": False,
572
- "use_long_term": True,
573
- "visualize": False,
574
- "weights": "pretrained_models/matanyone.pth"
575
- }
576
-
577
- # Merge with model.cfg if present; apply minimal overrides
578
- cfg = getattr(self.model, "cfg", default_cfg) or default_cfg
579
- if isinstance(cfg, dict):
580
- cfg = dict(cfg)
581
- overrides = {
582
- "chunk_size": 1,
583
- "flip_aug": False,
584
- }
585
- cfg.update(overrides)
586
- cfg = EasyDict(cfg)
587
-
588
- # Build inference core
589
- try:
590
- self.core = core_cls(self.model, cfg=cfg)
591
- except TypeError:
592
- self.core = core_cls(self.model)
593
-
594
- # Some versions expose .to()
595
- try:
596
- if hasattr(self.core, "to"):
597
- self.core.to(self.device)
598
- except Exception:
599
- pass
600
-
601
- # Build stateful adapter
602
- max_edge = int(os.environ.get("MATANYONE_MAX_EDGE", "768"))
603
- target_pixels = int(os.environ.get("MATANYONE_TARGET_PIXELS", "600000"))
604
- self.adapter = _MatAnyoneSession(
605
- self.core,
606
- device=self.device,
607
- model_dtype=model_dtype,
608
- use_autocast=use_autocast,
609
- autocast_dtype=autocast_dtype,
610
- max_edge=max_edge,
611
- target_pixels=target_pixels,
612
- )
613
  self.load_time = time.time() - t0
614
- logger.info(f"MatAnyone loaded in {self.load_time:.2f}s")
615
- return self.adapter
616
-
 
 
 
 
 
617
  except Exception as e:
 
618
  logger.error(f"Failed to load MatAnyone: {e}")
619
  logger.debug(traceback.format_exc())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
620
  return None
621
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
622
  def cleanup(self):
623
- """Release model/core and clear CUDA cache."""
624
- self.adapter = None
625
- self.core = None
626
- if self.model:
627
- try:
628
- del self.model
629
- except Exception:
630
- pass
631
- self.model = None
632
  if torch.cuda.is_available():
633
  torch.cuda.empty_cache()
634
-
635
  def get_info(self) -> Dict[str, Any]:
636
- """Lightweight status for UI/self-check."""
637
  return {
638
- "loaded": self.adapter is not None,
639
  "model_id": self.model_id,
640
- "device": self.device,
641
  "load_time": self.load_time,
642
- "model_type": type(self.model).__name__ if self.model else None,
 
643
  }
644
-
645
- def debug_shapes(self, image, mask, tag: str = ""):
646
- """Quick shape/dtype logger."""
647
- try:
648
- tv_img = torch.as_tensor(image)
649
- tv_msk = torch.as_tensor(mask) if mask is not None else None
650
- logger.info(f"[{tag}:image] shape={tuple(tv_img.shape)} dtype={tv_img.dtype}")
651
- if tv_msk is not None:
652
- logger.info(f"[{tag}:mask ] shape={tuple(tv_msk.shape)} dtype={tv_msk.dtype}")
653
- except Exception as e:
654
- logger.info(f"[{tag}] debug error: {e}")
655
-
656
-
657
- # ============================================================================
658
- # 8) PUBLIC SYMBOLS
659
- # ============================================================================
660
- __all__ = [
661
- "MatAnyoneLoader",
662
- "_MatAnyoneSession",
663
- "_to_bchw",
664
- "_resize_bchw",
665
- "_to_chw_image",
666
- "_to_1hw_mask",
667
- "_to_b1hw_alpha",
668
- "_to_2d_alpha_numpy",
669
- "_compute_scaled_size",
670
- "debug_shapes",
671
- ]
672
-
673
-
674
- # ============================================================================
675
- # 9) CLI DEMO (OPTIONAL QUICK TEST)
676
- # ============================================================================
677
- if __name__ == "__main__":
678
- import sys
679
- import cv2 # only for demo
680
- logging.basicConfig(level=logging.INFO)
681
- device = "cuda" if torch.cuda.is_available() else "cpu"
682
-
683
- if len(sys.argv) < 2:
684
- print(f"Usage: {sys.argv[0]} image.jpg [mask.png]")
685
- raise SystemExit(1)
686
-
687
- image_path = sys.argv[1]
688
- mask_path = sys.argv[2] if len(sys.argv) > 2 else None
689
-
690
- img_bgr = cv2.imread(image_path, cv2.IMREAD_COLOR)
691
- if img_bgr is None:
692
- print(f"Could not load image {image_path}")
693
- raise SystemExit(2)
694
- # OpenCV → RGB
695
- img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
696
-
697
- mask = None
698
- if mask_path:
699
- mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)
700
- if mask is not None and mask.max() > 1:
701
- mask = (mask.astype(np.float32) / 255.0)
702
-
703
- loader = MatAnyoneLoader(device=device)
704
- session = loader.load()
705
- if not session:
706
- print("Failed to load MatAnyone")
707
- raise SystemExit(3)
708
-
709
- alpha = session(img_rgb, mask if mask is not None else np.ones(img_rgb.shape[:2], np.float32))
710
- cv2.imwrite("alpha_out.png", (np.clip(alpha, 0, 1) * 255).astype(np.uint8))
711
- print("Alpha matte written to alpha_out.png")
 
1
  #!/usr/bin/env python3
2
  # -*- coding: utf-8 -*-
3
  """
4
+ MatAnyone Loader - Official InferenceCore API Implementation
5
+ ============================================================
6
+ Fixed to use official MatAnyone API to resolve tensor dimension issues.
7
+ No manual tensor manipulation - let InferenceCore handle everything internally.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  """
9
 
 
 
 
 
10
  import os
11
  import time
12
  import logging
13
+ import tempfile
14
  import traceback
15
+ from pathlib import Path
16
+ from typing import Optional, Dict, Any, Tuple
17
 
18
  import numpy as np
19
  import torch
20
+ import cv2
 
 
 
21
 
22
  logger = logging.getLogger(__name__)
23
 
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  class MatAnyoneLoader:
26
  """
27
+ Official MatAnyone loader using InferenceCore API.
28
+ This fixes the tensor dimension mismatch by using the official API
29
+ which handles all tensor dimensions internally.
30
  """
31
+
32
  def __init__(self, device: str = "cuda", cache_dir: str = "./checkpoints/matanyone_cache"):
33
+ self.device = self._select_device(device)
34
  self.cache_dir = cache_dir
35
  os.makedirs(self.cache_dir, exist_ok=True)
36
+
37
+ self.processor = None
 
38
  self.model_id = "PeiqingYang/MatAnyone"
39
  self.load_time = 0.0
40
+ self.loaded = False
41
+ self.load_error = None
42
+ self.temp_dir = Path(tempfile.mkdtemp())
43
+
44
+ def _select_device(self, pref: str) -> str:
45
+ """Select best available device."""
46
+ pref = (pref or "").lower()
47
+ if pref.startswith("cuda"):
48
+ return "cuda" if torch.cuda.is_available() else "cpu"
49
+ if pref == "cpu":
50
+ return "cpu"
51
+ return "cuda" if torch.cuda.is_available() else "cpu"
52
+
53
+ def load(self) -> bool:
54
+ """Load MatAnyone using official InferenceCore API."""
55
+ if self.loaded:
56
+ return True
57
+
 
 
 
 
 
 
 
 
 
 
 
 
58
  logger.info(f"Loading MatAnyone from HF: {self.model_id} (device={self.device})")
59
  t0 = time.time()
60
+
61
  try:
62
+ # Import the official API
63
+ from matanyone.inference.inference_core import InferenceCore
64
+
65
+ # Use official API - this handles ALL tensor dimensions internally
66
+ # No manual tensor reshaping needed!
67
+ self.processor = InferenceCore(self.model_id)
68
+
69
+ self.loaded = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  self.load_time = time.time() - t0
71
+ logger.info(f"MatAnyone loaded successfully via InferenceCore API in {self.load_time:.2f}s")
72
+ return True
73
+
74
+ except ImportError as e:
75
+ self.load_error = f"MatAnyone not installed: {e}"
76
+ logger.error(f"Failed to import MatAnyone. Install with: pip install git+https://github.com/pq-yang/MatAnyone.git@main")
77
+ return False
78
+
79
  except Exception as e:
80
+ self.load_error = str(e)
81
  logger.error(f"Failed to load MatAnyone: {e}")
82
  logger.debug(traceback.format_exc())
83
+ return False
84
+
85
+ def process_video(self, video_path: str, mask_path: str, output_dir: Optional[str] = None,
86
+ max_size: int = 720, save_frames: bool = False) -> Tuple[Optional[str], Optional[str]]:
87
+ """
88
+ Process video using official MatAnyone API.
89
+
90
+ Args:
91
+ video_path: Path to input video
92
+ mask_path: Path to first frame mask
93
+ output_dir: Output directory (uses temp if None)
94
+ max_size: Maximum resolution (-1 for original)
95
+ save_frames: Whether to save individual frames
96
+
97
+ Returns:
98
+ (foreground_path, alpha_path) or (None, None) on error
99
+ """
100
+ if not self.loaded:
101
+ if not self.load():
102
+ logger.error(f"MatAnyone not loaded: {self.load_error}")
103
+ return None, None
104
+
105
+ if output_dir is None:
106
+ output_dir = str(self.temp_dir)
107
+
108
+ try:
109
+ # Use official API - no tensor manipulation needed!
110
+ # The API handles all dimension requirements internally
111
+ foreground_path, alpha_path = self.processor.process_video(
112
+ input_path=str(video_path),
113
+ mask_path=str(mask_path),
114
+ output_path=str(output_dir),
115
+ max_size=max_size,
116
+ save_frames=save_frames
117
+ )
118
+
119
+ logger.info(f"MatAnyone processing complete: fg={foreground_path}, alpha={alpha_path}")
120
+ return foreground_path, alpha_path
121
+
122
+ except Exception as e:
123
+ logger.error(f"MatAnyone processing failed: {e}")
124
+ logger.debug(traceback.format_exc())
125
+ return None, None
126
+
127
+ def process_frames_to_alpha(self, frames: np.ndarray, initial_mask: np.ndarray,
128
+ output_dir: Optional[str] = None) -> Optional[np.ndarray]:
129
+ """
130
+ Process video frames and return alpha masks.
131
+ This is a compatibility wrapper for frame-based processing.
132
+
133
+ Args:
134
+ frames: Video frames as numpy array (T, H, W, C) or list
135
+ initial_mask: First frame mask (H, W) with values 0-255
136
+ output_dir: Optional output directory
137
+
138
+ Returns:
139
+ Alpha masks array (T, H, W) or None on error
140
+ """
141
+ if not self.loaded:
142
+ if not self.load():
143
+ return None
144
+
145
+ if output_dir is None:
146
+ output_dir = str(self.temp_dir)
147
+
148
+ # Save frames as temporary video
149
+ temp_video_path = Path(output_dir) / "temp_input.mp4"
150
+ temp_mask_path = Path(output_dir) / "temp_mask.png"
151
+
152
+ try:
153
+ # Convert frames to video
154
+ if isinstance(frames, list):
155
+ frames = np.stack(frames)
156
+
157
+ # Ensure correct format
158
+ if frames.ndim == 5: # (B, C, T, H, W) or similar
159
+ # Take first batch, rearrange to (T, H, W, C)
160
+ frames = frames[0]
161
+ if frames.shape[0] == 3: # Channels first
162
+ frames = frames.transpose(1, 2, 3, 0)
163
+ elif frames.ndim == 4 and frames.shape[1] == 3: # (T, C, H, W)
164
+ frames = frames.transpose(0, 2, 3, 1)
165
+
166
+ # Write video
167
+ fps = 30
168
+ height, width = frames.shape[1:3]
169
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
170
+ out = cv2.VideoWriter(str(temp_video_path), fourcc, fps, (width, height))
171
+
172
+ for frame in frames:
173
+ if frame.dtype in (np.float32, np.float64):
174
+ frame = (frame * 255).astype(np.uint8)
175
+ if frame.shape[-1] == 3:
176
+ frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
177
+ out.write(frame)
178
+ out.release()
179
+
180
+ # Save mask
181
+ if initial_mask.dtype in (np.float32, np.float64):
182
+ initial_mask = (initial_mask * 255).astype(np.uint8)
183
+ cv2.imwrite(str(temp_mask_path), initial_mask)
184
+
185
+ # Process with official API
186
+ _, alpha_path = self.process_video(
187
+ str(temp_video_path),
188
+ str(temp_mask_path),
189
+ str(output_dir)
190
+ )
191
+
192
+ if alpha_path:
193
+ # Load alpha video and return as array
194
+ return self._load_alpha_video(alpha_path)
195
+
196
  return None
197
+
198
+ except Exception as e:
199
+ logger.error(f"Frame processing failed: {e}")
200
+ return None
201
+ finally:
202
+ # Cleanup temp files
203
+ if temp_video_path.exists():
204
+ temp_video_path.unlink()
205
+ if temp_mask_path.exists():
206
+ temp_mask_path.unlink()
207
+
208
+ def _load_alpha_video(self, alpha_video_path: str) -> Optional[np.ndarray]:
209
+ """Load alpha video and return as numpy array."""
210
+ try:
211
+ cap = cv2.VideoCapture(str(alpha_video_path))
212
+ frames = []
213
+
214
+ while True:
215
+ ret, frame = cap.read()
216
+ if not ret:
217
+ break
218
+ # Convert to grayscale if needed
219
+ if len(frame.shape) == 3:
220
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
221
+ frames.append(frame / 255.0) # Normalize to 0-1
222
+
223
+ cap.release()
224
+ return np.array(frames) if frames else None
225
+
226
+ except Exception as e:
227
+ logger.error(f"Failed to load alpha video: {e}")
228
+ return None
229
+
230
  def cleanup(self):
231
+ """Cleanup temporary files and release resources."""
232
+ self.processor = None
233
+
234
+ # Clean temp directory
235
+ if self.temp_dir.exists():
236
+ import shutil
237
+ shutil.rmtree(self.temp_dir, ignore_errors=True)
238
+
239
+ # Clear CUDA cache if available
240
  if torch.cuda.is_available():
241
  torch.cuda.empty_cache()
242
+
243
  def get_info(self) -> Dict[str, Any]:
244
+ """Get model information."""
245
  return {
246
+ "loaded": self.loaded,
247
  "model_id": self.model_id,
248
+ "device": str(self.device),
249
  "load_time": self.load_time,
250
+ "error": self.load_error,
251
+ "api": "InferenceCore (official)"
252
  }
253
+
254
+ def reset(self):
255
+ """Reset the processor for a new video."""
256
+ # The official API handles session management internally
257
+ # Just log that reset was called
258
+ logger.info("MatAnyone session reset requested (handled by InferenceCore)")
259
+
260
+ # Compatibility method for existing code that might call this
261
+ def __call__(self, image, mask=None, **kwargs):
262
+ """
263
+ Direct call compatibility wrapper.
264
+ For single frame processing or backwards compatibility.
265
+ """
266
+ if isinstance(image, (list, np.ndarray)) and mask is not None:
267
+ # Process as frames
268
+ if not isinstance(image, np.ndarray):
269
+ image = np.array(image)
270
+ if image.ndim == 3: # Single frame
271
+ image = image[np.newaxis, ...]
272
+
273
+ alphas = self.process_frames_to_alpha(image, mask)
274
+ if alphas is not None and len(alphas) > 0:
275
+ return alphas[0] if alphas.shape[0] == 1 else alphas
276
+
277
+ # Fallback
278
+ logger.warning("Direct call to MatAnyoneLoader not fully supported with official API")
279
+ return mask if mask is not None else np.zeros(image.shape[:2], dtype=np.float32)
280
+
281
+
282
+ # For backwards compatibility - expose session class name even though we don't use it
283
+ _MatAnyoneSession = MatAnyoneLoader # Alias for compatibility
284
+
285
+
286
+ __all__ = ["MatAnyoneLoader", "_MatAnyoneSession"]