"""双卡合同拒绝隐式降级;进程协议不依赖CUDA即可验证。""" import json import os from pathlib import Path import sys import pytest from llm_services import runner, video_profiles TP2 = 'minimax-h3-fl2va-bf16-tp2-v1' UUIDS = ['GPU-84ed9d05-893b-5c7e-0833-b5c34a12ba33', 'GPU-6f547b70-7a25-70cb-e134-888402be61e2'] def request(tmp_path, **parameters): image = tmp_path / 'anchor.png' image.write_bytes(b'image-placeholder-not-decoded-in-validation') return {'task_type': 'video.generate', 'input': {'prompt': '鹏振翅穿越云层', 'image_path': str(image)}, 'parameters': {'profile': TP2, **parameters}, 'output_dir': str(tmp_path / 'outputs' / 'job')} def test_tp2_is_explicit_first_frame_profile_and_preserves_real_crop(tmp_path): normalized = runner.validate_request(request(tmp_path, num_frames=145), workspace=tmp_path) assert normalized['parameters']['profile'] == TP2 assert normalized['parameters']['num_frames'] == 145 assert video_profiles.native_frames(145) == 158 assert normalized['parameters']['upscale'] is False @pytest.mark.parametrize('frames', [146, 169, 337]) def test_tp2_only_accepts_qualified_frame_range(tmp_path, frames): with pytest.raises(ValueError, match='145|6|TP2'): runner.validate_request(request(tmp_path, num_frames=frames), workspace=tmp_path) @pytest.mark.parametrize('changes', [{'upscale': True}, {'conditioning_mode': 'first_last_frame'}]) def test_tp2_rejects_uncertified_processing(tmp_path, changes): with pytest.raises(ValueError, match='TP2|tp2|Unsupported'): runner.validate_request(request(tmp_path, **changes), workspace=tmp_path) def test_tp2_needs_first_frame(tmp_path): payload = request(tmp_path) payload['input'].pop('image_path') with pytest.raises(ValueError, match='first|首帧'): runner.validate_request(payload, workspace=tmp_path) def test_tp2_enabled_independently_of_single_gpu(tmp_path): from llm_services.store import Settings settings = Settings(tmp_path / 'app', tmp_path, video_generation_enabled=True) with pytest.raises(ValueError, match='certified|enabled'): video_profiles.validate_submission(settings, {'profile': TP2}) settings.video_generation_tp2_poc_enabled = True video_profiles.validate_submission(settings, {'profile': TP2}) cap = video_profiles.capabilities(settings) assert cap['available'] is True and cap['tp2']['available'] is False def test_tp2_cannot_enter_legacy_single_gpu_model_stage(tmp_path, monkeypatch): from llm_services import adapters, h3 monkeypatch.setattr(h3, 'run', lambda request: pytest.fail('TP2 reached old H3 runtime')) normalized = runner.validate_request(request(tmp_path), workspace=tmp_path) with pytest.raises(ValueError, match='supervisor'): adapters.run_stage(normalized, 'model') def test_two_members_and_cuda_order_are_required(monkeypatch): from llm_services.h3_tp2 import lease_members_from_env members = [{'uuid': u, 'index': i + 1} for i, u in enumerate(UUIDS)] monkeypatch.setenv('LLM_GPU_LEASE_MEMBERS', json.dumps(members)) monkeypatch.setenv('LLM_GPU_UUID', UUIDS[0]) monkeypatch.setenv('CUDA_VISIBLE_DEVICES', ','.join(UUIDS)) assert lease_members_from_env() == members monkeypatch.setenv('CUDA_VISIBLE_DEVICES', ','.join(reversed(UUIDS))) with pytest.raises(ValueError, match='order|visibility'): lease_members_from_env() monkeypatch.setenv('CUDA_VISIBLE_DEVICES', ','.join(UUIDS)) monkeypatch.setenv('LLM_GPU_LEASE_MEMBERS', json.dumps([members[0], members[0]])) with pytest.raises(ValueError, match='unique|duplicate'): lease_members_from_env() def test_explicit_phase_preemption_propagates_after_cleanup(tmp_path): from llm_services.h3_tp2 import raise_phase_failure from llm_services.adapters import GpuPreempted from llm_services.runner import StageProcessFailed error = StageProcessFailed('child failed') (tmp_path / 'phase-prepare-error-0.json').write_text(json.dumps( {'type': 'GpuPreempted', 'message': 'second GPU has external work'})) with pytest.raises(GpuPreempted, match='second GPU'): raise_phase_failure(tmp_path, 'prepare', error) # 清理失败不能被同一份抢占记录降格成可重试,让卡只接受明确的阶段退出。 cleanup = RuntimeError('descendants could not be released') with pytest.raises(RuntimeError, match='could not be released'): raise_phase_failure(tmp_path, 'prepare', cleanup) def test_state_codec_preserves_nested_tensor_layout_and_rejects_objects(tmp_path): torch = pytest.importorskip('torch') pytest.importorskip('safetensors') from llm_services.h3_tp2_state import save_state, load_state state = {'values': {'x': torch.tensor([1., 2.], dtype=torch.float32), 'layout': [(3, torch.tensor([1, 0], dtype=torch.int64))], 'none': None}, 'kwargs_mapping': {'denoiser_input_fields': ['position_ids', 'token_tags']}} save_state(tmp_path, 'prepared', state) loaded = load_state(tmp_path, 'prepared', device='cpu') assert loaded['values']['x'].dtype == torch.float32 assert loaded['values']['x'].tolist() == [1., 2.] assert isinstance(loaded['values']['layout'][0], tuple) assert loaded['values']['layout'][0][1].tolist() == [1, 0] assert loaded['kwargs_mapping'] == state['kwargs_mapping'] with pytest.raises(ValueError, match='Unsupported'): save_state(tmp_path, 'unsafe', {'obj': object()}) with pytest.raises(ValueError, match='state|name'): load_state(tmp_path, '../prepared', device='cpu') @pytest.mark.skipif(os.name != 'posix', reason='Linux rank identity and process groups') def test_fixed_ranks_inherit_group_and_failure_reaps_peer(tmp_path): from llm_services.h3_tp2 import run_fixed_ranks rank_script = tmp_path / 'rank.py' rank_script.write_text('import os,time,json,sys\nfrom pathlib import Path\n' 'r=int(os.environ["LOCAL_RANK"])\n' 'Path(sys.argv[1],str(r)+".json").write_text(json.dumps({"pid":os.getpid(),"pgid":os.getpgrp()}))\n' 'if r==1: time.sleep(.5); sys.exit(7)\n' 'time.sleep(30)\n') with pytest.raises(RuntimeError, match='rank|Rank'): run_fixed_ranks([sys.executable, str(rank_script), str(tmp_path)], env=dict(os.environ), directory=tmp_path, timeout=8) for rank in (0, 1): identity = json.loads((tmp_path / f'{rank}.json').read_text()) assert identity['pgid'] == os.getpgrp() import psutil assert not psutil.pid_exists(identity['pid']) @pytest.mark.skipif(os.name != 'posix', reason='Linux process groups and reparented children') def test_fast_successful_rank_cannot_leave_orphan_before_next_phase(tmp_path): import psutil from llm_services.h3_tp2 import run_fixed_ranks script = tmp_path / 'fast-rank.py' script.write_text('import os,sys,time,subprocess\nfrom pathlib import Path\n' 'time.sleep(.05)\n' 'c=subprocess.Popen([sys.executable,"-c","import time;time.sleep(30)"])\n' 'Path(sys.argv[1],os.environ["LOCAL_RANK"]+".pid").write_text(str(c.pid))\n' 'os._exit(0)\n') try: run_fixed_ranks([sys.executable, str(script), str(tmp_path)], env=dict(os.environ), directory=tmp_path, timeout=8) for rank in (0, 1): pid = int((tmp_path / f'{rank}.pid').read_text()) assert not psutil.pid_exists(pid) or psutil.Process(pid).status() == psutil.STATUS_ZOMBIE finally: for path in tmp_path.glob('*.pid'): try: process = psutil.Process(int(path.read_text())) if process.status() != psutil.STATUS_ZOMBIE: process.kill() except psutil.NoSuchProcess: pass