cmvr-visual/inference/llm_services/h3_tp2_phase.py

532 lines
28 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""一次性 H3 TP2 阶段;由持有双卡租约的同 PGID supervisor 启动。"""
from __future__ import annotations
import argparse
import hashlib
import importlib.metadata
import json
import os
import re
import sys
import time
from pathlib import Path
from .h3_tp2_state import (
MODEL_REPO,
MODEL_REVISION,
PROFILE,
RUNTIME_REVISION,
_atomic_json,
_binding,
_directory,
load_state,
save_state,
)
LAYOUT = ('position_ids', 'token_tags', 'video_indices', 'audio_indices', 'text_indices')
PREPARED = ('prompt_embeds', 'latents', 'audio_latents', *LAYOUT, 'height', 'width', 'num_frames',
'num_latent_frames', 'latent_height', 'latent_width', 'num_audio_latents',
'num_condition_video_rows', 'num_condition_audio_rows', 'num_inference_steps', 'attention_kwargs')
def restore_pipeline_state(value, state_class):
if type(value) is not dict or set(value) != {'values', 'kwargs_mapping'}:
raise ValueError('Invalid pipeline state schema')
values, mapping = value['values'], value['kwargs_mapping']
if type(values) is not dict or type(mapping) is not dict:
raise ValueError('Invalid pipeline state mapping')
categories = {}
for category, names in mapping.items():
if type(category) is not str or type(names) is not list:
raise ValueError('Invalid pipeline kwargs mapping')
for name in names:
if type(name) is not str or name not in values or name in categories:
raise ValueError('Pipeline mapping refers to missing or duplicate field')
categories[name] = category
state = state_class()
for name, item in values.items():
state.set(name, item, kwargs_type=categories.get(name))
return state
def _members(phase):
try:
members = json.loads(os.environ['LLM_GPU_LEASE_MEMBERS'])
except (KeyError, ValueError) as exc:
raise ValueError('Missing or invalid TP2 GPU members') from exc
if (type(members) is not list or len(members) != 2
or any(type(m) is not dict or set(m) != {'uuid', 'index'}
or type(m['uuid']) is not str
or re.fullmatch(r'GPU-[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}', m['uuid']) is None
or type(m['index']) is not int or m['index'] < 0 for m in members)
or members[0]['uuid'].lower() == members[1]['uuid'].lower()
or members[0]['index'] == members[1]['index']
or os.environ.get('LLM_GPU_UUID') != members[0]['uuid']):
raise ValueError('Invalid or duplicate TP2 GPU members/primary UUID')
visible = ','.join(m['uuid'] for m in members) if phase == 'denoise' else members[0]['uuid']
if os.environ.get('CUDA_VISIBLE_DEVICES') != visible:
raise ValueError('Phase GPU visibility does not match lease order')
return members
def _rank(phase):
if phase != 'denoise':
return 0
try:
rank, local, world = (int(os.environ[n]) for n in ('RANK', 'LOCAL_RANK', 'WORLD_SIZE'))
except (ValueError, KeyError) as exc:
raise ValueError('Denoise requires explicit RANK/LOCAL_RANK/WORLD_SIZE') from exc
if world != 2 or rank not in (0, 1) or local != rank:
raise ValueError('Denoise requires two fixed local ranks')
return rank
def _identity(phase, rank, members, directory):
if os.name != 'posix':
raise RuntimeError('H3 TP2 phases require Linux process identity')
expected = int(os.environ.get('LLM_GPU_EXPECTED_PGID', '0'))
if expected < 1 or os.getpgrp() != expected:
raise RuntimeError('TP2 phase escaped the expected job PGID')
fields = Path('/proc/self/stat').read_text().rsplit(')', 1)[1].split()
binding = _binding()
if binding['request_sha256'] is None:
raise ValueError('TP2 phases require request/group binding')
record = {'pid': os.getpid(), 'start': fields[19], 'pgid': os.getpgrp(), 'phase': phase,
'rank': rank, 'local_rank': rank, 'uuid': members[rank]['uuid'] if phase == 'denoise' else members[0]['uuid'],
'group_token': binding['group_token'], 'request_sha256': binding['request_sha256']}
_atomic_json(directory / f'phase-{phase}-rank-{rank}.json', record)
return record
def _ownership():
# 运行中的模型已占用显存;这里只问两张卡的权威归属,不重复要求空闲76GiB。
from .h3_tp2 import check_group
check_group(initial=False)
def _configure(phase, rank, members):
_ownership()
import torch
from .adapters import memory_fraction
expected_count = 2 if phase == 'denoise' else 1
if not torch.cuda.is_available() or torch.cuda.device_count() != expected_count:
raise RuntimeError('CUDA devices do not match phase visibility')
device = torch.device('cuda', rank if phase == 'denoise' else 0)
torch.cuda.set_device(device)
props = torch.cuda.get_device_properties(device)
actual = str(getattr(props, 'uuid', '')).lower().removeprefix('gpu-')
intended = members[rank if phase == 'denoise' else 0]['uuid'].lower().removeprefix('gpu-')
if actual != intended:
raise RuntimeError('CUDA rank UUID differs from leased GPU')
torch.cuda.set_per_process_memory_fraction(memory_fraction(props.total_memory), device=device)
torch.cuda.reset_peak_memory_stats(device)
torch.set_num_threads(min(int(os.environ.get('OMP_NUM_THREADS', '8')), os.cpu_count() or 1))
return torch, device
def _runtime():
import diffusers
if diffusers.__version__ != '0.43.0':
raise RuntimeError('TP2 requires the pinned Diffusers v0.43.0 runtime')
prefix = Path(sys.prefix).resolve()
source_name = getattr(diffusers, '__file__', None)
if not isinstance(source_name, str) or not Path(source_name).is_absolute():
raise RuntimeError('Diffusers source must belong to the current isolated environment')
source = Path(source_name).resolve()
if not source.is_file() or not source.is_relative_to(prefix):
raise RuntimeError('Diffusers source is outside the current environment prefix')
try:
distribution = importlib.metadata.distribution('diffusers')
if Path(distribution.locate_file('diffusers/__init__.py')).resolve() != source:
raise RuntimeError('Diffusers source differs from its installed distribution metadata')
raw = distribution.read_text('direct_url.json')
provenance = json.loads(raw) if raw else {}
if not isinstance(provenance, dict):
raise TypeError('Invalid Diffusers installed provenance')
except (OSError, ValueError, TypeError, importlib.metadata.PackageNotFoundError) as exc:
raise RuntimeError('Cannot verify Diffusers installed provenance') from exc
vcs = provenance.get('vcs_info')
if vcs is not None:
installed_commit = vcs.get('commit_id') if isinstance(vcs, dict) else None
if (not isinstance(vcs, dict) or vcs.get('vcs') != 'git'
or provenance.get('url') not in {'https://github.com/huggingface/diffusers',
'https://github.com/huggingface/diffusers.git'}
or installed_commit != RUNTIME_REVISION):
raise RuntimeError('Diffusers git source revision/commit differs from TP2 contract')
proof = 'git_direct_url'
else:
# archive安装没有vcs_info;版本号不能代替提交证据,只接受部署时已校验的锁。
expected_hash = 'c5ae262ee572007f4fa7ae0ecd53692204c3940cc0d0ff4a72b9db03f7352340'
lock_path = prefix / 'cmvr-runtime-lock.json'
if (lock_path.is_symlink() or not lock_path.is_file() or lock_path.stat().st_size > 65536):
raise RuntimeError('Diffusers source revision requires a verified archive provenance lock')
try:
lock = json.loads(lock_path.read_text(encoding='utf-8'))
runtime = lock['new_runtime']
locked_source = Path(runtime['source'])
if (lock['diffusers_source_revision'] != RUNTIME_REVISION
or lock['archive_sha256'] != expected_hash
or runtime['diffusers'] != diffusers.__version__
or not locked_source.is_absolute() or locked_source.resolve() != source):
raise RuntimeError('Diffusers archive lock revision/hash/source mismatch')
archive = provenance.get('archive_info', {})
if not isinstance(archive, dict) or 'dir_info' in provenance:
raise RuntimeError('Diffusers archive provenance does not match the runtime lock')
hashes = archive.get('hashes', {})
if not isinstance(hashes, dict) or hashes.get('sha256', expected_hash) != expected_hash:
raise RuntimeError('Diffusers archive provenance hash differs from the runtime lock')
if archive.get('hash', 'sha256=' + expected_hash) != 'sha256=' + expected_hash:
raise RuntimeError('Diffusers archive provenance hash differs from the runtime lock')
installed_commit = lock['diffusers_source_revision']
except (OSError, ValueError, KeyError, TypeError) as exc:
raise RuntimeError('Cannot verify Diffusers archive runtime lock') from exc
proof = 'archive_lock'
return {'diffusers_version': diffusers.__version__, 'diffusers_source_revision': installed_commit,
'installed_source_revision': installed_commit, 'provenance_type': proof}
def _request(path):
path = Path(path)
if not path.is_absolute() or path.is_symlink() or not path.is_file() or path.stat().st_size > 1024 ** 2:
raise ValueError('Phase request must be an absolute regular JSON file')
request = json.loads(path.read_text(encoding='utf-8'))
if type(request) is not dict:
raise ValueError('Invalid TP2 request')
digest = hashlib.sha256(json.dumps(request, sort_keys=True, separators=(',', ':'),
ensure_ascii=False, allow_nan=False).encode('utf-8')).hexdigest()
if digest != os.environ.get('LLM_TP2_REQUEST_SHA256'):
raise ValueError('Phase request hash differs from original request')
p, inputs = request.get('parameters', {}), request.get('input', {})
from .video_profiles import is_native_av, is_tp2
if p.get('profile') != os.environ.get('LLM_TP2_PROFILE', PROFILE):
raise ValueError('TP2 request profile differs from state binding')
if (request.get('task_type') != 'video.generate' or not is_tp2(p)
or not inputs.get('image_path') or inputs.get('last_image_path')
or inputs.get('negative_prompt') or p.get('upscale') is not False
or 'guidance_scale' in p or p.get('fps') != 24
or (p.get('width'), p.get('height')) not in {(1344, 768), (768, 1344)}):
raise ValueError('TP2 phase only accepts its explicit first-frame, non-upscale profiles')
from .video_profiles import native_frames
if is_native_av(p):
if type(p.get('num_frames')) is not int or p['num_frames'] not in (124, 141, 158):
raise ValueError('Native TP2 requires full native frames 124, 141 or 158')
elif type(p['num_frames']) is not int or not 25 <= p['num_frames'] <= 145 or p['num_frames'] % 4 != 1:
raise ValueError('TP2 supports qualified requested frames 25..145 in 4n+1')
native_frames(p['num_frames'])
if (type(p.get('seed')) is not int or not 0 <= p['seed'] <= 2 ** 32 - 1
or type(p.get('num_inference_steps')) is not int or not 2 <= p['num_inference_steps'] <= 100):
raise ValueError('Invalid TP2 seed or step count')
return request
def _pipeline(blocks_dict, model, names, torch):
from diffusers.modular_pipelines.minimax_h3.modular_pipeline import (
MiniMaxH3ModularPipeline,
)
from diffusers.modular_pipelines.modular_pipeline import SequentialPipelineBlocks
blocks = SequentialPipelineBlocks.from_blocks_dict(blocks_dict)
pipe = MiniMaxH3ModularPipeline(blocks=blocks, pretrained_model_name_or_path=model, local_files_only=True)
pipe.load_components(names=names, dtype=torch.bfloat16, pretrained_model_name_or_path=model,
local_files_only=True)
missing = [name for name in names if getattr(pipe, name, None) is None]
if missing:
raise RuntimeError(f'TP2 required components failed to load: {missing}')
return pipe
def _parameter_dtypes(model, torch, device, *, tp=False):
from torch.distributed.tensor import DTensor, Shard
keep = model._keep_in_fp32_modules or []
summary, total = {}, 0
for name, parameter in model.named_parameters():
local = parameter.to_local() if isinstance(parameter, DTensor) else parameter
expected = torch.float32 if any(part in name.split('.') for part in keep) else torch.bfloat16
if local.is_meta or local.device != device or local.dtype != expected:
raise RuntimeError(f'Official dtype/device contract failed for {name}: {local.dtype}/{local.device}')
total += local.numel() * local.element_size()
summary[str(local.dtype)] = summary.get(str(local.dtype), 0) + local.numel()
result = {'parameters_by_dtype': summary, 'local_parameter_bytes': total}
if tp:
import fnmatch
count = 0
for pattern, style in model._tp_plan.items():
modules = [(name, m) for name, m in model.named_modules() if fnmatch.fnmatchcase(name, pattern)]
if not modules:
raise RuntimeError(f'TP plan did not resolve: {pattern}')
dim = 1 if style in ('rowwise', 'rowwise_split_input') else 0
for name, module in modules:
weight = module.weight
if (not isinstance(weight, DTensor) or len(weight.placements) != 1
or not isinstance(weight.placements[0], Shard) or weight.placements[0].dim != dim
or weight.to_local().shape[dim] * 2 != weight.shape[dim]):
raise RuntimeError(f'TP2 weight was not correctly sharded: {name}')
count += 1
rope = model.rope.inv_freq
if rope.is_meta or rope.dtype != torch.float32 or rope.device != device:
raise RuntimeError('RoPE inv_freq must remain FP32 on the rank device')
frequency = (1 / (model.config.rope_theta ** (
torch.arange(0, 2 * model.config.rope_freq_dim, 2, dtype=torch.float32)
/ (2 * model.config.rope_freq_dim)))).to(device)
if not torch.equal(rope, frequency):
raise RuntimeError('RoPE inv_freq differs from official FP32 construction')
result.update(tp_sharded_weights=count, rope_dtype=str(rope.dtype))
return result
def _prepare(request, directory, torch, device):
from diffusers.hooks import apply_group_offloading
from diffusers.modular_pipelines.minimax_h3.before_denoise import (
MiniMaxH3FL2VAPrepareLatentsStep,
MiniMaxH3PrepareConditionLatentsStep,
MiniMaxH3PrepareLatentsStep,
MiniMaxH3PrepareLayoutStep,
)
from diffusers.modular_pipelines.minimax_h3.before_encoder import (
MiniMaxH3ResizeStep,
)
from diffusers.modular_pipelines.minimax_h3.encoders import (
MiniMaxH3FL2VATextEncoderStep,
MiniMaxH3KeyframeVaeEncoderStep,
)
from diffusers.modular_pipelines.modular_pipeline import PipelineState
from PIL import Image
from .h3 import _verified_model
from .video_profiles import native_frames
model = _verified_model()
config = json.loads((Path(model) / 'transformer' / 'config.json').read_text())
if (tuple(config['patch_size']) != (1, 2, 2) or config['in_channels'] != 24
or config['audio_in_channels'] != 32):
raise RuntimeError('Model geometry does not match standalone H3 block fallbacks')
pipe = _pipeline({'resize': MiniMaxH3ResizeStep, 'text_encoder': MiniMaxH3FL2VATextEncoderStep,
'vae_encoder': MiniMaxH3KeyframeVaeEncoderStep, 'prepare_layout': MiniMaxH3PrepareLayoutStep,
'prepare_condition_latents': MiniMaxH3PrepareConditionLatentsStep,
'prepare_latents': MiniMaxH3PrepareLatentsStep,
'prepare_latents_fl2va': MiniMaxH3FL2VAPrepareLatentsStep}, model,
['text_encoder', 'tokenizer', 'processor', 'vae', 'scheduler'], torch)
pipe.text_encoder.requires_grad_(False)
_ownership()
apply_group_offloading(pipe.text_encoder.model, offload_type='leaf_level', onload_device=device,
offload_device=torch.device('cpu'), use_stream=False, low_cpu_mem_usage=False,
record_stream=False)
pipe.vae.to(device)
dtypes = _parameter_dtypes(pipe.vae, torch, device)
p, inputs = request['parameters'], request['input']
with Image.open(inputs['image_path']) as image:
state = PipelineState(values={'prompt': inputs['prompt'], 'image': image.convert('RGB'),
'height': p['height'], 'width': p['width'], 'num_frames': native_frames(p['num_frames']),
'num_inference_steps': p['num_inference_steps'], 'attention_kwargs': None,
'generator': torch.Generator('cpu').manual_seed(p['seed'])})
with torch.inference_mode():
_, state = pipe.blocks(pipe, state)
values = {name: state.get(name) for name in PREPARED}
if any(values[name] is None for name in PREPARED if name != 'attention_kwargs'):
raise RuntimeError('Prepare produced incomplete TP2 state')
save_state(directory, 'prepared', {'values': values, 'kwargs_mapping': {'denoiser_input_fields': list(LAYOUT)}})
return {'native_frames': values['num_frames'], 'requested_frames': p['num_frames'], 'vae': dtypes,
'conditioner_precision': str(pipe.text_encoder.dtype),
'state_shapes': {k: list(v.shape) for k, v in values.items() if isinstance(v, torch.Tensor)}}
def _validate_prepared(value, torch):
if type(value) is not dict or set(value) != {'values', 'kwargs_mapping'}:
raise ValueError('Invalid prepared state')
values = value['values']
if set(values) != set(PREPARED) or value['kwargs_mapping'] != {'denoiser_input_fields': list(LAYOUT)}:
raise ValueError('Prepared state fields/layout mapping differ from contract')
for name in ('latents', 'audio_latents'):
if not isinstance(values[name], torch.Tensor) or values[name].dtype != torch.float32:
raise ValueError('Prepared noise rows must be FP32 tensors')
for name in ('token_tags', 'video_indices', 'audio_indices', 'text_indices'):
if not isinstance(values[name], torch.Tensor) or values[name].dtype != torch.int64:
raise ValueError('Prepared layout indices must be int64')
if values['position_ids'].dtype != torch.float64 or values['prompt_embeds'].dtype != torch.bfloat16:
raise ValueError('Prepared position/conditioner dtype differs from official contract')
if (values['latents'].ndim != 2 or values['latents'].shape[-1] != 96
or values['audio_latents'].ndim != 2 or values['audio_latents'].shape[-1] != 32
or values['prompt_embeds'].ndim != 3 or values['prompt_embeds'].shape[0] != 1
or values['prompt_embeds'].shape[-1] != 5120):
raise ValueError('Prepared latent row geometry differs from official contract')
def _denoise(request, directory, rank, torch, device):
import datetime
from urllib.parse import unquote, urlparse
from diffusers import MiniMaxH3Transformer3DModel, TensorParallelConfig
from diffusers.modular_pipelines.minimax_h3.before_denoise import (
MiniMaxH3SetTimestepsStep,
)
from diffusers.modular_pipelines.minimax_h3.decoders import (
MiniMaxH3AfterDenoiseStep,
)
from diffusers.modular_pipelines.minimax_h3.denoise import MiniMaxH3DenoiseStep
from diffusers.modular_pipelines.modular_pipeline import PipelineState
from .h3 import _verified_model
uri = os.environ.get('LLM_TP2_RENDEZVOUS', '')
parsed = urlparse(uri)
if (parsed.scheme != 'file' or parsed.netloc or parsed.query or parsed.fragment
or Path(unquote(parsed.path)) != directory / 'rendezvous'):
raise ValueError('Rendezvous must be the private phase directory file URI')
model = _verified_model()
value = load_state(directory, 'prepared', device=device)
_validate_prepared(value, torch)
state = restore_pipeline_state(value, PipelineState)
torch.distributed.init_process_group('nccl', init_method=uri, rank=rank, world_size=2,
timeout=datetime.timedelta(seconds=180))
try:
_ownership()
transformer = MiniMaxH3Transformer3DModel.from_pretrained(model, subfolder='transformer',
dtype=torch.bfloat16, parallel_config=TensorParallelConfig(tp_degree=2),
local_files_only=True, use_safetensors=True, low_cpu_mem_usage=True)
transformer.requires_grad_(False)
dtypes = _parameter_dtypes(transformer, torch, device, tp=True)
pipe = _pipeline({'set_timesteps': MiniMaxH3SetTimestepsStep, 'denoise': MiniMaxH3DenoiseStep,
'after_denoise': MiniMaxH3AfterDenoiseStep}, model,
['scheduler', 'audio_scheduler'], torch)
pipe.update_components(transformer=transformer)
_ownership()
with torch.inference_mode():
_, state = pipe.blocks(pipe, state)
values = denoised_values(state, request, torch)
latents = values['latents']
if rank == 0:
save_state(directory, 'denoised', {'values': values, 'kwargs_mapping': {}})
return {'transformer': dtypes, 'latent_shape': list(latents.shape),
'native_frames': state.get('num_frames'), 'steps': request['parameters']['num_inference_steps']}
finally:
# supervisor在失败时清理所有rank;此处不加可能永久等待失联同伴的barrier。
if torch.distributed.is_initialized():
torch.distributed.destroy_process_group()
def denoised_values(state, request, torch):
from .video_profiles import is_native_av
latents = state.get('latents')
if (latents is None or latents.dtype != torch.float32 or latents.ndim != 5 or latents.shape[:2] != (1, 24)
or not torch.isfinite(latents).all().item()):
raise RuntimeError('Denoise returned invalid unpacked video latents')
values = {'latents': latents}
if is_native_av(request['parameters']):
audio = state.get('audio_latents')
count = round(request['parameters']['num_frames'] / 24 * 40)
if (audio is None or audio.dtype != torch.float32 or tuple(audio.shape) != (2, 32, count)
or not torch.isfinite(audio).all().item()):
raise RuntimeError('Denoise returned invalid unpacked native audio latents')
values['audio_latents'] = audio
return values
def _decode(request, directory, torch, device):
import numpy as np
from diffusers.modular_pipelines.minimax_h3.decoders import MiniMaxH3VideoDecodeStep
from diffusers.modular_pipelines.modular_pipeline import PipelineState
from diffusers.utils.export_utils import encode_video
from .adapters import _new_file
from .h3 import _verified_model, select_video_frames
from .runner import confined_path
from .video_profiles import is_native_av, native_frames
model = _verified_model()
value = load_state(directory, 'denoised', device=device)
p = request['parameters']
native_av = is_native_av(p)
fields = {'latents', 'audio_latents'} if native_av else {'latents'}
if (set(value) != {'values', 'kwargs_mapping'} or set(value['values']) != fields
or value['kwargs_mapping'] != {}):
raise ValueError('Invalid denoised state fields')
latents = value['values']['latents']
native = native_frames(p['num_frames'])
expected = (1, 24, (native - 5) // 17 * 5 + 2, p['height'] // 16, p['width'] // 16)
if tuple(latents.shape) != expected or latents.dtype != torch.float32 or not torch.isfinite(latents).all().item():
raise ValueError('Invalid denoised video geometry/precision')
blocks, names = {'video_decode': MiniMaxH3VideoDecodeStep}, ['vae']
if native_av:
from diffusers.modular_pipelines.minimax_h3.decoders import MiniMaxH3AudioDecodeStep
audio = value['values']['audio_latents']
count = round(native / 24 * 40)
if (tuple(audio.shape) != (2, 32, count) or audio.dtype != torch.float32
or not torch.isfinite(audio).all().item()):
raise ValueError('Invalid denoised native audio geometry/precision')
blocks['audio_decode'] = MiniMaxH3AudioDecodeStep
names.append('audio_vae')
pipe = _pipeline(blocks, model, names, torch)
_ownership()
pipe.vae.to(device)
dtypes = _parameter_dtypes(pipe.vae, torch, device)
if native_av:
pipe.audio_vae.to(device)
state = PipelineState(values={**value['values'], 'output_type': 'np'})
with torch.inference_mode():
_, state = pipe.blocks(pipe, state)
videos = state.get('videos')
if videos is None or len(videos) != 1:
raise RuntimeError('Decode returned no single video')
array = np.asarray(select_video_frames(videos[0], requested=p['num_frames'], native=native))
if (array.shape != (p['num_frames'], p['height'], p['width'], 3)
or not np.issubdtype(array.dtype, np.floating) or not np.isfinite(array).all()
or array.min() < 0 or array.max() > 1):
raise RuntimeError('Decode returned invalid video shape/range')
output = confined_path(request['output_dir'])
output.mkdir(parents=True, exist_ok=True)
target = _new_file(output, 'video_raw.mp4')
_ownership()
paths, native_metadata = [target], {}
if native_av:
from .native_av import export_native_av
audio_target = _new_file(output, 'audio_native.wav')
native_metadata['native_av'] = export_native_av(array, state.get('audio'), state.get('sampling_rate'),
target, audio_target, encode_video)
paths.append(audio_target)
else:
encode_video(array, fps=24, output_path=str(target))
details = {'profile': p['profile'], 'precision': 'official mixed BF16/FP32', 'model': model,
'repo': MODEL_REPO, 'revision': MODEL_REVISION, 'diffusers_source_revision': RUNTIME_REVISION,
'requested_frames': p['num_frames'], 'native_frames': native, 'parameters': p,
'audio': 'native stereo audio preserved' if native_av else 'native audio omitted from video; independent audio assembly',
**native_metadata}
_atomic_json(directory / 'decoded.json', {'paths': [str(path.resolve()) for path in paths], 'metadata': details})
return {'vae': dtypes, 'output': str(target.resolve()), 'requested_frames': p['num_frames'], 'native_frames': native}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--phase', choices=('prepare', 'denoise', 'decode'), required=True)
parser.add_argument('--request', required=True)
parser.add_argument('--directory', required=True)
args = parser.parse_args(argv)
started, torch, device, report, directory, rank = time.monotonic(), None, None, {}, None, 0
try:
directory = _directory(args.directory)
rank = _rank(args.phase)
request = _request(args.request)
members = _members(args.phase)
report['identity'] = _identity(args.phase, rank, members, directory)
torch, device = _configure(args.phase, rank, members)
report.update(_runtime())
result = (_prepare(request, directory, torch, device) if args.phase == 'prepare' else
_denoise(request, directory, rank, torch, device) if args.phase == 'denoise' else
_decode(request, directory, torch, device))
report.update(result, completed=True)
return 0
except Exception as exc: # noqa: BLE001 — 进程边界必须保留明确失败类型给supervisor。
report.update(completed=False, error={'type': type(exc).__name__, 'message': str(exc)})
if directory is not None:
_atomic_json(directory / f'phase-{args.phase}-error-{rank}.json', report['error'])
print(f'TP2 {args.phase} failed: {type(exc).__name__}: {exc}', file=sys.stderr)
return 1
finally:
report.update(phase=args.phase, rank=rank, elapsed_seconds=time.monotonic() - started)
if torch is not None and device is not None:
report.update(peak_allocated_bytes=torch.cuda.max_memory_allocated(device),
peak_reserved_bytes=torch.cuda.max_memory_reserved(device))
if directory is not None:
name = f'phase-denoise-{rank}.json' if args.phase == 'denoise' else f'phase-{args.phase}.json'
_atomic_json(directory / name, report)
if __name__ == '__main__':
raise SystemExit(main())