From 81787e02437874425f04030ee2a89cefaa5a0884 Mon Sep 17 00:00:00 2001 From: liuchenbing Date: Sun, 22 Nov 2026 00:36:07 +0800 Subject: [PATCH] fix(auto): detect Ascend NPU and configure Ray/server config by device type Detect Ascend NPUs alongside CUDA GPUs in _ServerTools via torch.npu and npu-smi info -l fallback, propagate device_type into generated server_config.yaml device groups and meshes, and start Ray nodes with ASCEND_RT_VISIBLE_DEVICES and --resources={"NPU": n} on NPU hosts while preserving existing CUDA behavior. Signed-off-by: liuchenbing --- src/twinkle_client/auto/agent/server_tools.py | 109 ++++++++-- tests/twinkle_client/test_auto_agent_tools.py | 192 ++++++++++++++++++ 2 files changed, 281 insertions(+), 20 deletions(-) diff --git a/src/twinkle_client/auto/agent/server_tools.py b/src/twinkle_client/auto/agent/server_tools.py index 2324dc547..a41e6bb76 100644 --- a/src/twinkle_client/auto/agent/server_tools.py +++ b/src/twinkle_client/auto/agent/server_tools.py @@ -55,10 +55,10 @@ async def _tool_start_server( def _start(): sampler_list = samplers or [] - # Step 1: Detect hardware & compute GPU partition - total_hw_gpus = self._detect_gpu_count() + # Step 1: Detect hardware & compute device partition + device_type, total_hw_gpus = self._detect_accelerator() if total_hw_gpus == 0: - return {'status': 'error', 'error': 'No GPUs detected. Cannot start training server.'} + return {'status': 'error', 'error': 'No GPUs or NPUs detected. Cannot start training server.'} alloc = self._compute_gpu_allocation(sampler_list, train_gpus, total_hw_gpus) if 'error' in alloc: @@ -72,10 +72,11 @@ def _start(): port=port, backend=backend, samplers=sampler_list, + device_type=device_type, ) - # Step 3: Start Ray cluster (multi-node GPU partitioning) - ray_err = self._start_ray_cluster(t_gpus, sampler_gpu_total) + # Step 3: Start Ray cluster (multi-node device partitioning) + ray_err = self._start_ray_cluster(t_gpus, sampler_gpu_total, device_type=device_type) if ray_err: return {'status': 'error', 'error': ray_err} @@ -102,9 +103,34 @@ def _start(): return result @staticmethod - def _detect_gpu_count() -> int: - """Detect total hardware GPU count via nvidia-smi.""" + def _detect_npu_count_from_smi() -> int: + """Detect total Ascend NPU device count via `npu-smi info -l`.""" + import re + import subprocess as _sp + + try: + r = _sp.run( + ['npu-smi', 'info', '-l'], + capture_output=True, + text=True, + timeout=10, + ) + if r.returncode != 0: + return 0 + except (FileNotFoundError, OSError): + return 0 + + chip_counts = [int(m) for m in re.findall(r'^\s*Chip Count\s*:\s*(\d+)\b', r.stdout, re.MULTILINE)] + if chip_counts: + return sum(chip_counts) + total_match = re.search(r'^\s*Total Count\s*:\s*(\d+)\b', r.stdout, re.MULTILINE) + return int(total_match.group(1)) if total_match else 0 + + @staticmethod + def _detect_accelerator() -> tuple[str, int]: + """Detect host accelerator type ('cuda' or 'npu') and device count.""" import subprocess as _sp + try: r = _sp.run( ['nvidia-smi', '--query-gpu=index', '--format=csv,noheader'], @@ -113,10 +139,41 @@ def _detect_gpu_count() -> int: timeout=10, ) if r.returncode == 0: - return len([ln for ln in r.stdout.strip().split('\n') if ln.strip()]) + count = len([ln for ln in r.stdout.strip().split('\n') if ln.strip()]) + if count > 0: + return 'cuda', count except (FileNotFoundError, OSError): pass - return 0 + + try: + import torch + + if hasattr(torch, 'cuda') and torch.cuda.is_available(): + count = int(torch.cuda.device_count()) + if count > 0: + return 'cuda', count + try: + import torch_npu # noqa: F401 + except (ImportError, OSError): + pass + npu = getattr(torch, 'npu', None) + if npu is not None and npu.is_available(): + count = int(npu.device_count()) + if count > 0: + return 'npu', count + except (ImportError, AttributeError, RuntimeError): + pass + + npu_count = _ServerTools._detect_npu_count_from_smi() + if npu_count > 0: + return 'npu', npu_count + + return 'cuda', 0 + + @staticmethod + def _detect_gpu_count() -> int: + """Detect total hardware accelerator count (CUDA GPUs or Ascend NPUs).""" + return _ServerTools._detect_accelerator()[1] @staticmethod def _compute_gpu_allocation( @@ -146,12 +203,12 @@ def _compute_gpu_allocation( return {'train_gpus': t_gpus, 'sampler_gpus': sampler_gpu_total} @staticmethod - def _start_ray_cluster(train_gpus: int, sampler_gpus: int) -> str | None: - """Start Ray multi-node cluster with GPU partitioning. + def _start_ray_cluster(train_gpus: int, sampler_gpus: int, device_type: str = 'cuda') -> str | None: + """Start Ray multi-node cluster with accelerator partitioning. - Each role gets its own Ray node with dedicated CUDA_VISIBLE_DEVICES - so GPUs are indexed from 0 within each node. This prevents the - GPU ID mapping issues that occur with a single-node setup. + Each role gets its own Ray node with dedicated visible-device env vars + so devices are indexed from 0 within each node. This prevents the + device ID mapping issues that occur with a single-node setup. On a single machine, multiple raylets need separate --temp-dir to avoid being detected as "already running". @@ -162,6 +219,8 @@ def _start_ray_cluster(train_gpus: int, sampler_gpus: int) -> str | None: import tempfile from pathlib import Path + dev_type = (device_type or 'cuda').lower() + _sp.run(['ray', 'stop', '--force'], capture_output=True, timeout=15) # Create unique temp dirs so each `ray start` spawns a separate raylet @@ -176,14 +235,20 @@ def _ray_node( node_name: str = 'worker', ) -> str | None: env = os.environ.copy() - env['CUDA_VISIBLE_DEVICES'] = devices temp_dir = str(ray_base / node_name) cmd = ['ray', 'start', f'--temp-dir={temp_dir}'] if head: cmd += ['--head', '--port=6379', '--disable-usage-stats', '--include-dashboard=false'] else: cmd += ['--address=127.0.0.1:6379'] - cmd.append(f'--num-gpus={num_gpus}') + if dev_type == 'npu': + env['ASCEND_RT_VISIBLE_DEVICES'] = devices + if num_gpus > 0: + res_spec = json.dumps({'NPU': num_gpus}) + cmd.append(f'--resources={res_spec}') + else: + env['CUDA_VISIBLE_DEVICES'] = devices + cmd.append(f'--num-gpus={num_gpus}') r = _sp.run(cmd, capture_output=True, text=True, timeout=30, env=env) if r.returncode != 0 and 'already' not in r.stderr.lower(): return r.stderr.strip() @@ -354,6 +419,7 @@ def _generate_server_config( port: int = 8000, backend: str = 'transformers', samplers: list[dict] | None = None, + device_type: str = 'cuda', ) -> str: """Generate a server_config.yaml from template and return its path. @@ -366,6 +432,9 @@ def _generate_server_config( from pathlib import Path sampler_list = samplers or [] + dev_type = (device_type or 'cuda').lower() + if dev_type not in ('cuda', 'npu', 'mps'): + raise ValueError(f'Unsupported device_type: {device_type!r}') if backend not in ('transformers', 'megatron'): raise ValueError(f'Unsupported training backend: {backend!r}') if backend == 'megatron' and train_gpus < 2: @@ -438,10 +507,10 @@ def _short(mid: str) -> str: 'device_group': { 'name': 'model', 'ranks': train_gpus, - 'device_type': 'cuda', + 'device_type': dev_type, }, 'device_mesh': { - 'device_type': 'cuda', + 'device_type': dev_type, 'dp_size': train_gpus, }, 'queue_config': { @@ -516,7 +585,7 @@ def _short(mid: str) -> str: # Build device_mesh: include tp_size when tp>1 so that # world_size = tp*dp and slice_dp dispatch computes correct # rank_stride for DP data sharding. - mesh_config: dict = {'device_type': 'cuda', 'dp_size': s_dp} + mesh_config: dict = {'device_type': dev_type, 'dp_size': s_dp} if s_tp > 1: mesh_config['tp_size'] = s_tp @@ -534,7 +603,7 @@ def _short(mid: str) -> str: 'device_group': { 'name': s_name, 'ranks': s_total_gpus, - 'device_type': 'cuda', + 'device_type': dev_type, 'gpus_per_worker': s_tp, }, 'device_mesh': mesh_config, diff --git a/tests/twinkle_client/test_auto_agent_tools.py b/tests/twinkle_client/test_auto_agent_tools.py index 9d5ecc59d..d6fd281e2 100644 --- a/tests/twinkle_client/test_auto_agent_tools.py +++ b/tests/twinkle_client/test_auto_agent_tools.py @@ -127,3 +127,195 @@ def test_unsupported_training_backend_is_not_written(tmp_path, monkeypatch, back with pytest.raises(ValueError, match='Unsupported training backend'): ToolExecutor._generate_server_config('Qwen/student', train_gpus=1, backend=backend) assert not (tmp_path / '.cache' / 'twinkle' / 'server_config.yaml').exists() + + +def test_detect_accelerator_cuda_via_nvidia_smi(monkeypatch): + import subprocess + from types import SimpleNamespace + + monkeypatch.setattr( + subprocess, + 'run', + lambda *args, **kwargs: SimpleNamespace(returncode=0, stdout='0\n1\n2\n3\n', stderr=''), + ) + assert ToolExecutor._detect_accelerator() == ('cuda', 4) + assert ToolExecutor._detect_gpu_count() == 4 + + +def test_detect_accelerator_npu_via_torch(monkeypatch): + import subprocess + import torch + from types import SimpleNamespace + + def _no_nvidia(cmd, *args, **kwargs): + raise FileNotFoundError(cmd[0]) + + monkeypatch.setattr(subprocess, 'run', _no_nvidia) + monkeypatch.setattr(torch.cuda, 'is_available', lambda: False) + monkeypatch.setattr( + torch, + 'npu', + SimpleNamespace(is_available=lambda: True, device_count=lambda: 8), + raising=False, + ) + assert ToolExecutor._detect_accelerator() == ('npu', 8) + assert ToolExecutor._detect_gpu_count() == 8 + + +def test_detect_accelerator_npu_via_npu_smi_fallback(monkeypatch): + import subprocess + import torch + from types import SimpleNamespace + + monkeypatch.setattr(torch.cuda, 'is_available', lambda: False) + monkeypatch.setattr(torch, 'npu', None, raising=False) + + single_chip_out = ( + '\tTotal Count : 8\n\n' + + '\n'.join(f'\tNPU ID : {i}\n\tChip Count : 1\n' for i in range(8)) + ) + dual_chip_out = ( + '\tTotal Count : 4\n\n' + + '\n'.join(f'\tNPU ID : {i}\n\tChip Count : 2\n' for i in range(4)) + ) + + for smi_stdout in (single_chip_out, dual_chip_out): + def _run(cmd, *args, _out=smi_stdout, **kwargs): + if cmd[0] == 'nvidia-smi': + raise FileNotFoundError('nvidia-smi') + if cmd[:3] == ['npu-smi', 'info', '-l']: + return SimpleNamespace(returncode=0, stdout=_out, stderr='') + raise AssertionError(f'Unexpected command: {cmd}') + + monkeypatch.setattr(subprocess, 'run', _run) + assert ToolExecutor._detect_accelerator() == ('npu', 8) + assert ToolExecutor._detect_gpu_count() == 8 + + def _missing_all(cmd, *args, **kwargs): + raise FileNotFoundError(cmd[0]) + + monkeypatch.setattr(subprocess, 'run', _missing_all) + assert ToolExecutor._detect_accelerator() == ('cuda', 0) + assert ToolExecutor._detect_gpu_count() == 0 + + +@pytest.mark.parametrize('backend', ['transformers', 'megatron']) +@pytest.mark.parametrize('samplers', [[], [{'model_id': 'Qwen/teacher', 'engine': 'vllm', 'tp': 2, 'dp': 2}]]) +def test_generated_server_config_supports_npu_device_type(tmp_path, monkeypatch, backend, samplers): + from pathlib import Path + from twinkle.server.config import ServerConfig + + monkeypatch.setattr(Path, 'home', lambda: tmp_path) + path = ToolExecutor._generate_server_config( + 'Qwen/student', + train_gpus=2, + backend=backend, + samplers=samplers, + device_type='npu', + ) + config = ServerConfig.from_yaml(path) + model_app = next(app for app in config.applications if app.import_path == 'model') + assert model_app.args.device_group['device_type'] == 'npu' + assert model_app.args.device_mesh['device_type'] == 'npu' + assert config.training_config.models[0].device_type == 'npu' + proc_app = next(app for app in config.applications if app.import_path == 'processor') + assert proc_app.args.device_group['device_type'] == 'CPU' + if samplers: + sampler_app = next(app for app in config.applications if app.import_path == 'sampler') + assert sampler_app.args.device_group['device_type'] == 'npu' + assert sampler_app.args.device_mesh['device_type'] == 'npu' + + +def test_start_ray_cluster_npu_and_cuda_args(monkeypatch, tmp_path): + import subprocess + import tempfile + from types import SimpleNamespace + + monkeypatch.setattr(tempfile, 'gettempdir', lambda: str(tmp_path)) + monkeypatch.delenv('CUDA_VISIBLE_DEVICES', raising=False) + monkeypatch.delenv('ASCEND_RT_VISIBLE_DEVICES', raising=False) + + calls: list[tuple[list[str], dict[str, str] | None]] = [] + + def _fake_run(cmd, *args, **kwargs): + calls.append((list(cmd), kwargs.get('env'))) + return SimpleNamespace(returncode=0, stdout='', stderr='') + + monkeypatch.setattr(subprocess, 'run', _fake_run) + + assert ToolExecutor._start_ray_cluster(2, 2, device_type='npu') is None + npu_starts = [(cmd, env) for cmd, env in calls if cmd[:2] == ['ray', 'start']] + assert len(npu_starts) == 3 + + head_cmd, head_env = npu_starts[0] + assert '--head' in head_cmd + assert not any(arg.startswith('--num-gpus') for arg in head_cmd) + head_res = [arg.split('=', 1)[1] for arg in head_cmd if arg.startswith('--resources=')] + assert len(head_res) == 1 and json.loads(head_res[0]) == {'NPU': 2} + assert head_env is not None and head_env['ASCEND_RT_VISIBLE_DEVICES'] == '0,1' + assert 'CUDA_VISIBLE_DEVICES' not in head_env + + worker_cmd, worker_env = npu_starts[1] + assert not any(arg.startswith('--num-gpus') for arg in worker_cmd) + worker_res = [arg.split('=', 1)[1] for arg in worker_cmd if arg.startswith('--resources=')] + assert len(worker_res) == 1 and json.loads(worker_res[0]) == {'NPU': 2} + assert worker_env is not None and worker_env['ASCEND_RT_VISIBLE_DEVICES'] == '2,3' + + cpu_cmd, cpu_env = npu_starts[2] + assert not any(arg.startswith('--num-gpus') for arg in cpu_cmd) + assert not any(arg.startswith('--resources=') for arg in cpu_cmd) + assert cpu_env is not None and cpu_env['ASCEND_RT_VISIBLE_DEVICES'] == '' + + calls.clear() + assert ToolExecutor._start_ray_cluster(2, 2, device_type='cuda') is None + cuda_starts = [(cmd, env) for cmd, env in calls if cmd[:2] == ['ray', 'start']] + assert len(cuda_starts) == 3 + assert '--num-gpus=2' in cuda_starts[0][0] + assert cuda_starts[0][1] is not None and cuda_starts[0][1]['CUDA_VISIBLE_DEVICES'] == '0,1' + assert '--num-gpus=2' in cuda_starts[1][0] + assert cuda_starts[1][1] is not None and cuda_starts[1][1]['CUDA_VISIBLE_DEVICES'] == '2,3' + assert '--num-gpus=0' in cuda_starts[2][0] + assert cuda_starts[2][1] is not None and cuda_starts[2][1]['CUDA_VISIBLE_DEVICES'] == '' + + +@pytest.mark.asyncio +async def test_start_server_wires_detected_npu_end_to_end(monkeypatch): + executor = ToolExecutor(_Connection()) + captured: dict[str, object] = {} + + async def _not_running(url): + return False + + def _fake_config(model_id, train_gpus, port=8000, backend='transformers', samplers=None, device_type='cuda'): + captured['config_device_type'] = device_type + captured['config_train_gpus'] = train_gpus + return '/tmp/fake_server_config.yaml' + + def _fake_ray(train_gpus, sampler_gpus, device_type='cuda'): + captured['ray_device_type'] = device_type + captured['ray_train_gpus'] = train_gpus + return None + + monkeypatch.setattr(executor, '_check_server_health', _not_running) + monkeypatch.setattr(ToolExecutor, '_detect_accelerator', staticmethod(lambda: ('npu', 4))) + monkeypatch.setattr(ToolExecutor, '_generate_server_config', staticmethod(_fake_config)) + monkeypatch.setattr(ToolExecutor, '_start_ray_cluster', staticmethod(_fake_ray)) + monkeypatch.setattr( + ToolExecutor, + '_launch_server_process', + staticmethod(lambda config_path: (object(), '/tmp/fake_server.log', None)), + ) + monkeypatch.setattr( + ToolExecutor, + '_wait_server_ready', + staticmethod(lambda **kwargs: {'status': 'started', 'server_url': kwargs['server_url']}), + ) + + result = await executor._tool_start_server('Qwen/Qwen2.5-0.5B', train_gpus=2) + assert result['status'] == 'started' + assert captured == { + 'config_device_type': 'npu', + 'config_train_gpus': 2, + 'ray_device_type': 'npu', + 'ray_train_gpus': 2, + }