Skip to content

Multiprocess simple RL loop - #2158

Merged
acisseJZhong merged 16 commits into
pytorch:mainfrom
acisseJZhong:simple_rl_multigpu
Dec 22, 2025
Merged

acisseJZhong merged 16 commits into
pytorch:mainfrom
acisseJZhong:simple_rl_multigpu

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Dec 16, 2025 •

Copy link
Copy Markdown
Contributor

Borrowed part of the implementations from deterministic RL #1975 by @bwasti, set up simple RL running on multiple process.

Features added:

  • set up train and generator as Actors; potentially using an unified model definition from Torchtitan.
  • integrate with Monarch to run Torchtitan trainer on multiple processes using DDP, and vLLM generator using TP.

Added TODOs here: https://github.com/pytorch/torchtitan/blob/eb601cfc924b379b589af95bffee2a3a56f0a67f/torchtitan/experiments/rl/unified/README.md#todo

Command to run:

VLLM_BATCH_INVARIANT=1 VLLM_ATTENTION_BACKEND=FLASH_ATTN python3 torchtitan/experiments/rl/unified/simple_rl_multiprocess.py 

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Dec 16, 2025
@acisseJZhong
acisseJZhong force-pushed the simple_rl_multigpu branch 2 times, most recently from 42f704f to c638bba Compare December 16, 2025 21:35
@acisseJZhong
acisseJZhong requested review from tianyu-l, wwwjn and zhxchen17 and removed request for tianyu-l December 19, 2025 19:57

# Initialize vLLM engine
self.vllm_engine = VLLMRolloutEngine(model_path, tp_size=self.tp_size)
self.tokenizer = AutoTokenizer.from_pretrained(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This field is not used in trivial_reward_function, pls remove. Also in this work we should try not depend on HF transformers


# Notify generator of updated weights
if self.generator:
titan_state = self.model.state_dict()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since everything is titan, can we call it e.g. trainer_model_states?

)

enable_batch_invariant_backward_mode()
else:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's error out, instead of silent fall back

# Load dataset
if use_real_dataset:
print(f"Loading GSM8K dataset ({num_dataset_samples} samples)...")
prompt_texts, expected_answers = load_gsm8k_dataset(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should refactor this into a torchtitan dataset, maybe as a TODO

return model


def create_parallel_dims_from_vllm_config(vllm_config: VllmConfig) -> ParallelDims:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there seems already exist such a function in parallelism_utils.py

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ooops forgot to remove.

Comment on lines +28 to +29
UNIFIED = "unified"
BATCH_INVARIANT = "batch_invariant"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's the difference between the two?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this refer to Bram's approch - Creating a vllm-compatible torchtitan model and achieve bit-wise identity between train and inference. Can we rename it to be "vllm-compat" to align with current file structure? Ideally in the future we need to achieve batch-invariant in unified model path as well

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unified is using Torchtitan's model definition but only replace with vllm attention(what @wwwjn has implemented in vllm wrapper)

batch_invariant is running Bram's vllm compatible model for training, and vllm model for inference, which could achieve bitwise determinism.

Eventually we need to remove batch_invariant mode and achieve batch invariance under unified mode.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unified cannot do training, can it? If so and if it can achieve batch-invariance, we don't have to include the other version.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

right now it can't, facing some forward context issue when using vllm.Attention. We should either switch to using VLLMCompatibleFlashAttention in both trainer and generator, or add backward to vllm.Attention.

After that, we should remove the batch_invariant mode.

logger = logging.getLogger(__name__)


class ModelMode(str, Enum):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please add comments to the values

Comment on lines +28 to +29
UNIFIED = "unified"
BATCH_INVARIANT = "batch_invariant"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this refer to Bram's approch - Creating a vllm-compatible torchtitan model and achieve bit-wise identity between train and inference. Can we rename it to be "vllm-compat" to align with current file structure? Ideally in the future we need to achieve batch-invariant in unified model path as well



class ModelMode(str, Enum):
UNIFIED = "unified"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I remember you mentioned this simple RL script works with unified model mode, but in the description of PR it says "Integrate with Unified Model, right now it's using batch invariant mode". Does it work with unified model definition? If not, we should add comments here and clean up UNIFIED branch

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

right now unified model is not working yet as we are using VLLMAttention


apply_ddp(
self.model,
self.parallel_dims.world_mesh,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
self.parallel_dims.world_mesh,
self.parallel_dims.get_mesh("dp_replicate")

This part was refactored on main branch recently #1660

# Convert to vLLM-compat format (merged gate_up_proj, down_proj)
vllm_compat_state = torchtitan_to_vllm_compat(state_dict)
model.load_state_dict(vllm_compat_state, strict=False)
else:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How does it differs from model_mode == ModelMode.UNIFIED:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sry i might have not updated the code, we are replacing vllm attention in unified mode.

model: Loaded TorchTitan model
"""
# Load HuggingFace config
hf_config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Thoughts about how we should refactor this part later, we could avoid using transformers)
We don't need the hf_config if we are loading "standard" qwen3 model. By "standard" I mean the model size that already defined in qwen3/init.py.

An alternative way to do this is import qwen_args from this file, initialize a Qwen3ModelArgs() and Qwen3Model. If you'll need to load weights, use the same functions here is enough:

def load_weights(self, weights_iter):
"""
Load weights from HF checkpoint using the provided state dict adapter.
vLLM engine would call this function to load model weights.
Args:
weights_iter: Iterator of (name, tensor) pairs from HF checkpoint
Returns:
Set of loaded parameter names
"""
# Collect weights from iterator
hf_state_dict = {}
for name, tensor in weights_iter:
hf_state_dict[name] = tensor
# Use adapter to convert HF → TorchTitan format
adapter = self.state_dict_adapter(
model_args=self.config,
hf_assets_path=None,
)
torchtitan_state_dict = adapter.from_hf(hf_state_dict)
model_state_dict = {k: v for k, v in self.model.state_dict().items()}
# Convert to DTensor if target is DTensor
for name, tensor in torchtitan_state_dict.items():
if name in model_state_dict and isinstance(model_state_dict[name], DTensor):
target_dtensor = model_state_dict[name]
device_mesh = target_dtensor.device_mesh
torchtitan_state_dict[name] = DTensor.from_local(
tensor.to(device_mesh.device_type),
device_mesh=device_mesh,
placements=[Replicate()],
)
# Load state dict
set_model_state_dict(
model=self.model,
model_state_dict=torchtitan_state_dict,
options=StateDictOptions(strict=False),
)
loaded_params = {f"model.{name}" for name in torchtitan_state_dict.keys()}
return loaded_params

```
python torchtitan/experiments/rl/unified/infer.py --model torchtitan/experiments/deterministic_vllm_rl/example_checkpoint/qwen3-0.6B --tensor-parallel-size 2
python torchtitan/experiments/rl/unified/infer.py --model torchtitan/experiments/rl/example_checkpoint/Qwen3-0.6B --tensor-parallel-size 2

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add commands in README to run simple_rl_multiprocess.py?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I want to propose the following file structure under rl folder for easier understanding:

  • Actors/
    • trainer.py
    • generator.py
  • simple_rl_multiprocess.py: rl loop entrance for now
  • Unified/: one approach to define model
    • infer.py will live here for now, as inference is not our main goal, but a test script
  • vllm-compat/: another approach to define model
    • simple_rl.py: keep this under vllm-compat to make this folder self-contained for now. We could refactor/ remove it later

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we should maintain the vllm-compat copy. Your proposal sounds like we should maintain it and make it work with monarch. Any benefit? If no obvious benefit, we should make unified self-contained and eventually remove vllm-compat.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sg, then let's make them totally separate and create actors/ folder under unified

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sg, then let's make them totally separate and create actors/ folder under unified

)
index_file = os.path.join(self.temp_model_dir, "model.safetensors.index.json")

if len(shard_files) == 2 and os.path.exists(index_file):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This part is because HF weights are sharded into 2 safetensor files, but the trainer only write to one, we need to copy to matching the original hf format? We can leave a TODO here, all these copy thing can be removed once we use torchtitan checkpoint saving / loading.

nit: https://huggingface.co/Qwen/Qwen3-0.6B/tree/main this model only have 1 safetensor file, and not need all these complicated logic. And this code is too tight to 2 safetensor files

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yup this part I directly copied from simple rl, we should also get rid of the torchtitan_to_vllm and torchtitan_to_vllm_compat which seems confusing to me.

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

some nit comments

# Compute rewards using provided reward function
if reward_fn == trivial_reward_function:
rewards = reward_fn(completions, tokenizer, expected_answers, group_size)
rewards = reward_fn(completions, expected_answers, group_size)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no need for if else?


# Rebuild vLLM from source with CUDA 12.4
pip install -e .
uv pip install -e .

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are we recommending uv for everything now? Does pip alone not working?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am using uv env and pip is not working. I guess pip will still work if you are using conda env. I updated all commands to uv for consistency.

@acisseJZhong acisseJZhong changed the title [WIP] multiprocess simple rl Multiprocess simple rl loop Dec 22, 2025
@acisseJZhong acisseJZhong changed the title Multiprocess simple rl loop Multiprocess simple RL loop Dec 22, 2025
@acisseJZhong
acisseJZhong merged commit 4b3d25a into pytorch:main Dec 22, 2025
xrsrke pushed a commit to NousResearch/torchtitan that referenced this pull request Feb 13, 2026
Borrowed part of the implementations from deterministic RL
pytorch#1975 by @bwasti, set up
simple RL running on multiple process.

Features added:
- set up train and generator as Actors; potentially using an unified
model definition from Torchtitan.
- integrate with Monarch to run Torchtitan trainer on multiple processes
using DDP, and vLLM generator using TP.

Added TODOs here:
https://github.com/pytorch/torchtitan/blob/eb601cfc924b379b589af95bffee2a3a56f0a67f/torchtitan/experiments/rl/unified/README.md#todo

Command to run:
```
VLLM_BATCH_INVARIANT=1 VLLM_ATTENTION_BACKEND=FLASH_ATTN python3 torchtitan/experiments/rl/unified/simple_rl_multiprocess.py 
```
TXacs pushed a commit to McmillanTAC/torchtitan that referenced this pull request Apr 13, 2026
Borrowed part of the implementations from deterministic RL
pytorch#1975 by @bwasti, set up
simple RL running on multiple process.

Features added:
- set up train and generator as Actors; potentially using an unified
model definition from Torchtitan.
- integrate with Monarch to run Torchtitan trainer on multiple processes
using DDP, and vLLM generator using TP.

Added TODOs here:
https://github.com/pytorch/torchtitan/blob/eb601cfc924b379b589af95bffee2a3a56f0a67f/torchtitan/experiments/rl/unified/README.md#todo

Command to run:
```
VLLM_BATCH_INVARIANT=1 VLLM_ATTENTION_BACKEND=FLASH_ATTN python3 torchtitan/experiments/rl/unified/simple_rl_multiprocess.py 
```
ACharacterInASimulation pushed a commit to ACharacterInASimulation/torchtitan that referenced this pull request Apr 21, 2026
Borrowed part of the implementations from deterministic RL
pytorch#1975 by @bwasti, set up
simple RL running on multiple process.

Features added:
- set up train and generator as Actors; potentially using an unified
model definition from Torchtitan.
- integrate with Monarch to run Torchtitan trainer on multiple processes
using DDP, and vLLM generator using TP.

Added TODOs here:
https://github.com/pytorch/torchtitan/blob/eb601cfc924b379b589af95bffee2a3a56f0a67f/torchtitan/experiments/rl/unified/README.md#todo

Command to run:
```
VLLM_BATCH_INVARIANT=1 VLLM_ATTENTION_BACKEND=FLASH_ATTN python3 torchtitan/experiments/rl/unified/simple_rl_multiprocess.py 
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants