main
py 82 lines 2.63 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4 # unit test for `examples/features/torchrun/torchrun_example_offline.py`
5 import os
6 import random
7
8 import torch
9 import torch.distributed as dist
10
11 import vllm.envs as envs
12 from vllm import LLM, SamplingParams
13 from vllm.distributed.parallel_state import get_world_group
14
15 # By default, let PyTorch choose the WORLD backend for the current device
16 # type (legacy lazy-init path). When VLLM_DISTRIBUTED_USE_SPLIT_GROUP=1,
17 # use the explicit eager-init pattern required by `split_group` (mixed
18 # cpu:gloo,cuda:nccl backend + device_id binding).
19 if envs.VLLM_DISTRIBUTED_USE_SPLIT_GROUP:
20 local_rank = int(os.environ["LOCAL_RANK"])
21 torch.accelerator.set_device_index(local_rank)
22 dist.init_process_group(
23 backend="cpu:gloo,cuda:nccl",
24 device_id=torch.device(f"cuda:{local_rank}"),
25 )
26 else:
27 dist.init_process_group()
28
29 # Create prompts
30 prompts = [
31 "Hello, my name is",
32 "The president of the United States is",
33 "The capital of France is",
34 "The future of AI is",
35 ]
36
37 sampling_params = SamplingParams(temperature=0.8, top_p=0.95)
38
39 # set different `gpu_memory_utilization` for different ranks,
40 # to test if all ranks agree on the same kv cache configuration.
41 llm = LLM(
42 model="facebook/opt-125m",
43 tensor_parallel_size=2,
44 pipeline_parallel_size=int(os.getenv("PP_SIZE", 1)),
45 distributed_executor_backend="external_launcher",
46 gpu_memory_utilization=random.uniform(0.8, 0.92),
47 seed=0,
48 )
49
50 outputs = llm.generate(prompts, sampling_params)
51
52 cpu_group = get_world_group().cpu_group
53
54 torch_rank = dist.get_rank(group=cpu_group)
55
56
57 def test_consistent_across_ranks(obj):
58 if torch_rank == 0:
59 dist.broadcast_object_list([obj], src=0, group=cpu_group)
60 else:
61 container = [None]
62 dist.broadcast_object_list(container, src=0, group=cpu_group)
63 assert container[0] == obj
64
65
66 test_consistent_across_ranks(llm.llm_engine.vllm_config.cache_config.num_cpu_blocks)
67 test_consistent_across_ranks(llm.llm_engine.vllm_config.cache_config.num_gpu_blocks)
68
69 # make sure we can access the model parameters from the calling process
70 # of the `LLM` instance.
71 params = list(
72 llm.llm_engine.model_executor.driver_worker.worker.model_runner.model.parameters()
73 )
74 test_consistent_across_ranks(len(params))
75
76 # all ranks should have the same outputs
77 for output in outputs:
78 prompt = output.prompt
79 generated_text = output.outputs[0].text
80 test_consistent_across_ranks(prompt)
81 test_consistent_across_ranks(generated_text)
82 print(f"Rank {torch_rank}, Prompt: {prompt!r}, Generated text: {generated_text!r}")