SII-ChengqiLi commited on
Commit
462eb5d
·
verified ·
1 Parent(s): c1bf6a6

Add files using upload-large-folder tool

Browse files
.gitattributes CHANGED
@@ -58,3 +58,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ paper_conclusion_rl_train.jsonl filter=lfs diff=lfs merge=lfs -text
62
+ paper_conclusion_rl_test.jsonl filter=lfs diff=lfs merge=lfs -text
EasyR1/assets/easyr1_grpo.png ADDED

Git LFS Details

  • SHA256: abea6d96166d713ef03e1b0c4e6cbfcec65a83869dd31d9de41c3a887d04fa9a
  • Pointer size: 131 Bytes
  • Size of remote file: 866 kB
EasyR1/assets/qwen2_5_vl_7b_geo.png ADDED

Git LFS Details

  • SHA256: f54564a9bbe374df9c94cf6d0ed6a0ec575f5983caa77372008f43b856a8c1f0
  • Pointer size: 131 Bytes
  • Size of remote file: 106 kB
EasyR1/examples/format_prompt/android_gui.jinja ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are playing a number selection game. Your goal is to select the CORRECT number based on the traffic light color.
2
+
3
+ **Game Rules:**
4
+ - There are 3 numbers to choose from (positions: left=0, middle=1, right=2)
5
+ - A traffic light at the top shows ONE color: GREEN, RED, or YELLOW
6
+ - You must select the number that satisfies the rule for that color:
7
+ * **GREEN light**: Select the LARGEST number
8
+ * **RED light**: Select the SMALLEST number
9
+ * **YELLOW light**: Select the MIDDLE number (not largest, not smallest)
10
+
11
+ **Your Task:**
12
+ Look at the screenshot and identify:
13
+ 1. Which traffic light is ON (GREEN/RED/YELLOW)
14
+ 2. The three numbers shown
15
+ 3. Apply the rule for that color
16
+ 4. Output the position of the correct number
17
+
18
+ **Output Format:**
19
+ Output ONLY a single digit representing the position:
20
+ - 0 (left card)
21
+ - 1 (middle card)
22
+ - 2 (right card)
23
+
24
+ Do not include any explanation or other text.
25
+
26
+ ---
27
+
28
+ {{ content }}
EasyR1/verl/single_controller/base/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .worker import Worker
16
+ from .worker_group import ClassWithInitArgs, ResourcePool, WorkerGroup
17
+
18
+
19
+ __all__ = ["ClassWithInitArgs", "ResourcePool", "Worker", "WorkerGroup"]
EasyR1/verl/single_controller/base/decorator.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from enum import Enum, auto
16
+ from functools import wraps
17
+ from types import FunctionType
18
+ from typing import TYPE_CHECKING, Literal, Union
19
+
20
+ import ray
21
+
22
+ from ...protocol import DataProto, DataProtoFuture
23
+
24
+
25
+ if TYPE_CHECKING:
26
+ from .worker_group import WorkerGroup
27
+
28
+
29
+ # here we add a magic number of avoid user-defined function already have this attribute
30
+ MAGIC_ATTR = "attrs_3141562937"
31
+
32
+
33
+ class Dispatch(Enum):
34
+ RANK_ZERO = auto()
35
+ ONE_TO_ALL = auto()
36
+ ALL_TO_ALL = auto()
37
+ DP_COMPUTE = auto()
38
+ DP_COMPUTE_PROTO = auto()
39
+ DP_COMPUTE_PROTO_WITH_FUNC = auto()
40
+ DP_COMPUTE_METRIC = auto()
41
+
42
+
43
+ class Execute(Enum):
44
+ ALL = 0
45
+ RANK_ZERO = 1
46
+
47
+
48
+ def _split_args_kwargs_data_proto(chunks: int, *args, **kwargs):
49
+ splitted_args = []
50
+ for arg in args:
51
+ assert isinstance(arg, (DataProto, DataProtoFuture))
52
+ splitted_args.append(arg.chunk(chunks=chunks))
53
+
54
+ splitted_kwargs = {}
55
+ for key, value in kwargs.items():
56
+ assert isinstance(value, (DataProto, DataProtoFuture))
57
+ splitted_kwargs[key] = value.chunk(chunks=chunks)
58
+
59
+ return splitted_args, splitted_kwargs
60
+
61
+
62
+ def dispatch_one_to_all(worker_group: "WorkerGroup", *args, **kwargs):
63
+ args = tuple([arg] * worker_group.world_size for arg in args)
64
+ kwargs = {k: [v] * worker_group.world_size for k, v in kwargs.items()}
65
+ return args, kwargs
66
+
67
+
68
+ def dispatch_all_to_all(worker_group: "WorkerGroup", *args, **kwargs):
69
+ return args, kwargs
70
+
71
+
72
+ def collect_all_to_all(worker_group: "WorkerGroup", output):
73
+ return output
74
+
75
+
76
+ def _concat_data_proto_or_future(outputs: list[DataProto]) -> DataProto:
77
+ # make sure all the elements in output has the same type
78
+ for output in outputs:
79
+ assert type(output) is type(outputs[0])
80
+
81
+ output = outputs[0]
82
+
83
+ if isinstance(output, DataProto):
84
+ return DataProto.concat(outputs)
85
+ elif isinstance(output, ray.ObjectRef):
86
+ return DataProtoFuture.concat(outputs)
87
+ else:
88
+ raise NotImplementedError
89
+
90
+
91
+ def dispatch_dp_compute(worker_group: "WorkerGroup", *args, **kwargs):
92
+ for arg in args:
93
+ assert isinstance(arg, (tuple, list)) and len(arg) == worker_group.world_size
94
+
95
+ for value in kwargs.values():
96
+ assert isinstance(value, (tuple, list)) and len(value) == worker_group.world_size
97
+
98
+ return args, kwargs
99
+
100
+
101
+ def collect_dp_compute(worker_group: "WorkerGroup", outputs: list[DataProto]) -> list[DataProto]:
102
+ assert len(outputs) == worker_group.world_size
103
+ return outputs
104
+
105
+
106
+ def dispatch_dp_compute_data_proto(worker_group: "WorkerGroup", *args, **kwargs):
107
+ splitted_args, splitted_kwargs = _split_args_kwargs_data_proto(worker_group.world_size, *args, **kwargs)
108
+ return splitted_args, splitted_kwargs
109
+
110
+
111
+ def dispatch_dp_compute_data_proto_with_func(worker_group: "WorkerGroup", *args, **kwargs):
112
+ assert type(args[0]) is FunctionType # NOTE: The first one args is a function!
113
+ splitted_args, splitted_kwargs = _split_args_kwargs_data_proto(worker_group.world_size, *args[1:], **kwargs)
114
+ splitted_args_with_func = [[args[0]] * worker_group.world_size] + splitted_args
115
+ return splitted_args_with_func, splitted_kwargs
116
+
117
+
118
+ def collect_dp_compute_data_proto(worker_group: "WorkerGroup", outputs: list[DataProto]) -> DataProto:
119
+ for output in outputs:
120
+ assert isinstance(output, (DataProto, ray.ObjectRef)), f"Expect a DataProto, but got {type(output)}"
121
+
122
+ outputs = collect_dp_compute(worker_group, outputs)
123
+ return _concat_data_proto_or_future(outputs)
124
+
125
+
126
+ def get_predefined_dispatch_fn(dispatch_mode: Dispatch):
127
+ predefined_dispatch_mode_fn = {
128
+ Dispatch.ONE_TO_ALL: {
129
+ "dispatch_fn": dispatch_one_to_all,
130
+ "collect_fn": collect_all_to_all,
131
+ },
132
+ Dispatch.ALL_TO_ALL: {
133
+ "dispatch_fn": dispatch_all_to_all,
134
+ "collect_fn": collect_all_to_all,
135
+ },
136
+ Dispatch.DP_COMPUTE: {
137
+ "dispatch_fn": dispatch_dp_compute,
138
+ "collect_fn": collect_dp_compute,
139
+ },
140
+ Dispatch.DP_COMPUTE_PROTO: {
141
+ "dispatch_fn": dispatch_dp_compute_data_proto,
142
+ "collect_fn": collect_dp_compute_data_proto,
143
+ },
144
+ Dispatch.DP_COMPUTE_PROTO_WITH_FUNC: {
145
+ "dispatch_fn": dispatch_dp_compute_data_proto_with_func,
146
+ "collect_fn": collect_dp_compute_data_proto,
147
+ },
148
+ Dispatch.DP_COMPUTE_METRIC: {
149
+ "dispatch_fn": dispatch_dp_compute_data_proto,
150
+ "collect_fn": collect_dp_compute,
151
+ },
152
+ }
153
+ return predefined_dispatch_mode_fn[dispatch_mode]
154
+
155
+
156
+ def get_predefined_execute_fn(execute_mode: Execute):
157
+ """
158
+ Note that here we only asks execute_all and execute_rank_zero to be implemented
159
+ Leave the choice of how these two functions handle argument 'blocking' to users
160
+ """
161
+ predefined_execute_mode_fn = {
162
+ Execute.ALL: {"execute_fn_name": "execute_all"},
163
+ Execute.RANK_ZERO: {"execute_fn_name": "execute_rank_zero"},
164
+ }
165
+ return predefined_execute_mode_fn[execute_mode]
166
+
167
+
168
+ def _check_dispatch_mode(dispatch_mode: Union[Dispatch, dict[Literal["dispatch_fn", "collect_fn"], FunctionType]]):
169
+ assert isinstance(dispatch_mode, (Dispatch, dict)), (
170
+ f"dispatch_mode must be a Dispatch or a Dict. Got {dispatch_mode}"
171
+ )
172
+ if isinstance(dispatch_mode, dict):
173
+ necessary_keys = ["dispatch_fn", "collect_fn"]
174
+ for key in necessary_keys:
175
+ assert key in dispatch_mode, f"key {key} should be in dispatch_mode if it is a dictionary"
176
+
177
+
178
+ def _check_execute_mode(execute_mode: Execute):
179
+ assert isinstance(execute_mode, Execute), f"execute_mode must be a Execute. Got {execute_mode}"
180
+
181
+
182
+ def _materialize_futures(*args, **kwargs):
183
+ new_args = []
184
+ for arg in args:
185
+ if isinstance(arg, DataProtoFuture):
186
+ arg = arg.get()
187
+ # add more type to materialize
188
+ new_args.append(arg)
189
+
190
+ for key, value in kwargs.items():
191
+ if isinstance(value, DataProtoFuture):
192
+ kwargs[key] = value.get()
193
+
194
+ new_args = tuple(new_args)
195
+ return new_args, kwargs
196
+
197
+
198
+ def register(dispatch_mode=Dispatch.ALL_TO_ALL, execute_mode=Execute.ALL, blocking=True, materialize_futures=True):
199
+ _check_dispatch_mode(dispatch_mode=dispatch_mode)
200
+ _check_execute_mode(execute_mode=execute_mode)
201
+
202
+ def decorator(func):
203
+ @wraps(func)
204
+ def inner(*args, **kwargs):
205
+ if materialize_futures:
206
+ args, kwargs = _materialize_futures(*args, **kwargs)
207
+ return func(*args, **kwargs)
208
+
209
+ attrs = {"dispatch_mode": dispatch_mode, "execute_mode": execute_mode, "blocking": blocking}
210
+ setattr(inner, MAGIC_ATTR, attrs)
211
+ return inner
212
+
213
+ return decorator
EasyR1/verl/single_controller/base/register_center/ray.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import ray
16
+
17
+
18
+ @ray.remote
19
+ class WorkerGroupRegisterCenter:
20
+ def __init__(self, rank_zero_info):
21
+ self.rank_zero_info = rank_zero_info
22
+
23
+ def get_rank_zero_info(self):
24
+ return self.rank_zero_info
25
+
26
+
27
+ def create_worker_group_register_center(name, info):
28
+ return WorkerGroupRegisterCenter.options(name=name).remote(info)
EasyR1/verl/single_controller/base/worker.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ the class for Worker
16
+ """
17
+
18
+ import os
19
+ import socket
20
+ from dataclasses import dataclass
21
+ from typing import Tuple
22
+
23
+ import ray
24
+ import torch
25
+
26
+ from .decorator import Dispatch, Execute, register
27
+ from .register_center.ray import create_worker_group_register_center
28
+
29
+
30
+ @dataclass
31
+ class DistRankInfo:
32
+ tp_rank: int
33
+ dp_rank: int
34
+ pp_rank: int
35
+
36
+
37
+ @dataclass
38
+ class DistGlobalInfo:
39
+ tp_size: int
40
+ dp_size: int
41
+ pp_size: int
42
+
43
+
44
+ class WorkerHelper:
45
+ def _get_node_ip(self) -> str:
46
+ host_ipv4 = os.getenv("MY_HOST_IP", None)
47
+ host_ipv6 = os.getenv("MY_HOST_IPV6", None)
48
+ host_ip_by_env = host_ipv4 or host_ipv6
49
+ host_ip_by_sdk = ray._private.services.get_node_ip_address()
50
+
51
+ host_ip = host_ip_by_env or host_ip_by_sdk
52
+ return host_ip
53
+
54
+ def _get_free_port(self) -> int:
55
+ with socket.socket() as sock:
56
+ sock.bind(("", 0))
57
+ return sock.getsockname()[1]
58
+
59
+ def get_availale_master_addr_port(self) -> Tuple[str, str]:
60
+ return self._get_node_ip(), str(self._get_free_port())
61
+
62
+ def _get_pid(self):
63
+ return
64
+
65
+
66
+ class WorkerMeta:
67
+ keys = [
68
+ "WORLD_SIZE",
69
+ "RANK",
70
+ "LOCAL_WORLD_SIZE",
71
+ "LOCAL_RANK",
72
+ "MASTER_ADDR",
73
+ "MASTER_PORT",
74
+ "CUDA_VISIBLE_DEVICES",
75
+ ]
76
+
77
+ def __init__(self, store) -> None:
78
+ self._store = store
79
+
80
+ def to_dict(self):
81
+ return {f"_{key.lower()}": self._store.get(f"_{key.lower()}", None) for key in WorkerMeta.keys}
82
+
83
+
84
+ # we assume that in each WorkerGroup, there is a Master Worker
85
+ class Worker(WorkerHelper):
86
+ """A (distributed) worker."""
87
+
88
+ _world_size: int
89
+ _rank: int
90
+ _local_world_size: int
91
+ _local_rank: int
92
+ _master_addr: str
93
+ _master_port: str
94
+ _cuda_visible_devices: str
95
+
96
+ def __new__(cls, *args, **kwargs):
97
+ instance = super().__new__(cls)
98
+
99
+ # note that here we use int to distinguish
100
+ disable_worker_init = int(os.getenv("DISABLE_WORKER_INIT", 0))
101
+ if disable_worker_init:
102
+ return instance
103
+
104
+ rank = os.getenv("RANK", None)
105
+ worker_group_prefix = os.getenv("WG_PREFIX", None)
106
+
107
+ # when decorator @ray.remote applies, __new__ will be called while we don't want to apply _configure_before_init
108
+ if None not in [rank, worker_group_prefix] and "ActorClass(" not in cls.__name__:
109
+ instance._configure_before_init(f"{worker_group_prefix}_register_center", int(rank))
110
+
111
+ return instance
112
+
113
+ def _configure_before_init(self, register_center_name: str, rank: int):
114
+ assert isinstance(rank, int), f"rank must be int, instead of {type(rank)}"
115
+
116
+ if rank == 0:
117
+ master_addr, master_port = self.get_availale_master_addr_port()
118
+ rank_zero_info = {
119
+ "MASTER_ADDR": master_addr,
120
+ "MASTER_PORT": master_port,
121
+ }
122
+ self.register_center = create_worker_group_register_center(name=register_center_name, info=rank_zero_info)
123
+ os.environ.update(rank_zero_info)
124
+
125
+ def __init__(self, cuda_visible_devices=None) -> None:
126
+ # construct a meta from envrionment variable. Note that the import must be inside the class because it is executed remotely
127
+ world_size = int(os.getenv("WORLD_SIZE"))
128
+ rank = int(os.getenv("RANK"))
129
+ self._rank = rank
130
+ self._world_size = world_size
131
+
132
+ if "AMD" in torch.cuda.get_device_name():
133
+ os.environ["CUDA_VISIBLE_DEVICES"] = os.getenv("ROCR_VISIBLE_DEVICES")
134
+ os.environ["LOCAL_RANK"] = os.getenv("RAY_LOCAL_RANK")
135
+ cuda_visible_devices = os.getenv("LOCAL_RANK", "0")
136
+ torch.cuda.set_device(int(cuda_visible_devices))
137
+
138
+ master_addr = os.getenv("MASTER_ADDR")
139
+ master_port = os.getenv("MASTER_PORT")
140
+
141
+ local_world_size = int(os.getenv("LOCAL_WORLD_SIZE", "1"))
142
+ local_rank = int(os.getenv("LOCAL_RANK", "0"))
143
+
144
+ store = {
145
+ "_world_size": world_size,
146
+ "_rank": rank,
147
+ "_local_world_size": local_world_size,
148
+ "_local_rank": local_rank,
149
+ "_master_addr": master_addr,
150
+ "_master_port": master_port,
151
+ }
152
+ if cuda_visible_devices is not None:
153
+ store["_cuda_visible_devices"] = cuda_visible_devices
154
+
155
+ meta = WorkerMeta(store=store)
156
+ self._configure_with_meta(meta=meta)
157
+
158
+ def _configure_with_meta(self, meta: WorkerMeta):
159
+ """
160
+ This function should only be called inside by WorkerGroup
161
+ """
162
+ assert isinstance(meta, WorkerMeta)
163
+ self.__dict__.update(meta.to_dict()) # this is hacky
164
+ # print(f"__dict__: {self.__dict__}")
165
+ for key in WorkerMeta.keys:
166
+ val = self.__dict__.get(f"_{key.lower()}", None)
167
+ if val is not None:
168
+ # print(f"set {key} to {val}")
169
+ os.environ[key] = str(val)
170
+
171
+ os.environ["REDIS_STORE_SERVER_HOST"] = (
172
+ str(self._master_addr).replace("[", "").replace("]", "") if self._master_addr else ""
173
+ )
174
+
175
+ def get_master_addr_port(self):
176
+ return self._master_addr, self._master_port
177
+
178
+ def get_cuda_visible_devices(self):
179
+ cuda_visible_devices = os.getenv("CUDA_VISIBLE_DEVICES", "not set")
180
+ return cuda_visible_devices
181
+
182
+ def print_rank0(self, *args, **kwargs):
183
+ if self.rank == 0:
184
+ print(*args, **kwargs)
185
+
186
+ @property
187
+ def world_size(self):
188
+ return self._world_size
189
+
190
+ @property
191
+ def rank(self):
192
+ return self._rank
193
+
194
+ @register(dispatch_mode=Dispatch.DP_COMPUTE_PROTO_WITH_FUNC)
195
+ def execute_with_func_generator(self, func, *args, **kwargs):
196
+ ret_proto = func(self, *args, **kwargs)
197
+ return ret_proto
198
+
199
+ @register(dispatch_mode=Dispatch.ALL_TO_ALL, execute_mode=Execute.RANK_ZERO)
200
+ def execute_func_rank_zero(self, func, *args, **kwargs):
201
+ result = func(*args, **kwargs)
202
+ return result
EasyR1/verl/utils/checkpoint/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .checkpoint_manager import CHECKPOINT_TRACKER, find_latest_ckpt, remove_obsolete_ckpt
16
+
17
+
18
+ __all__ = ["CHECKPOINT_TRACKER", "find_latest_ckpt", "remove_obsolete_ckpt"]
EasyR1/verl/utils/logger/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from .logger import Tracker
17
+
18
+
19
+ __all__ = ["Tracker"]
EasyR1/verl/utils/logger/logger.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ A unified tracking interface that supports logging data to different backend
16
+ """
17
+
18
+ import json
19
+ import os
20
+ from abc import ABC, abstractmethod
21
+ from typing import Any, Optional, Union
22
+
23
+ import torch
24
+
25
+ from ..py_functional import convert_dict_to_str, flatten_dict, is_package_available, unflatten_dict
26
+ from .gen_logger import AggregateGenerationsLogger
27
+
28
+
29
+ if is_package_available("mlflow"):
30
+ import mlflow # type: ignore
31
+
32
+
33
+ if is_package_available("tensorboard"):
34
+ from torch.utils.tensorboard import SummaryWriter
35
+
36
+
37
+ if is_package_available("wandb"):
38
+ import wandb # type: ignore
39
+
40
+
41
+ if is_package_available("swanlab"):
42
+ import swanlab # type: ignore
43
+
44
+
45
+ class Logger(ABC):
46
+ @abstractmethod
47
+ def __init__(self, config: dict[str, Any]) -> None: ...
48
+
49
+ @abstractmethod
50
+ def log(self, data: dict[str, Any], step: int) -> None: ...
51
+
52
+ def finish(self) -> None:
53
+ pass
54
+
55
+
56
+ class ConsoleLogger(Logger):
57
+ def __init__(self, config: dict[str, Any]) -> None:
58
+ print("Config\n" + convert_dict_to_str(config))
59
+
60
+ def log(self, data: dict[str, Any], step: int) -> None:
61
+ print(f"Step {step}\n" + convert_dict_to_str(unflatten_dict(data)))
62
+
63
+
64
+ class FileLogger(Logger):
65
+ def __init__(self, config: dict[str, Any]) -> None:
66
+ self.config = config
67
+ print(f"Initializing logging file to {config['trainer']['save_checkpoint_path']}.")
68
+ os.makedirs(config["trainer"]["save_checkpoint_path"], exist_ok=True)
69
+ with open(os.path.join(config["trainer"]["save_checkpoint_path"], "experiment_config.json"), "w") as f:
70
+ json.dump(config, f, indent=2)
71
+
72
+ with open(os.path.join(config["trainer"]["save_checkpoint_path"], "experiment_log.jsonl"), "w") as f:
73
+ pass
74
+
75
+ with open(os.path.join(config["trainer"]["save_checkpoint_path"], "generations.log"), "w") as f:
76
+ pass
77
+
78
+ def log(self, data: dict[str, Any], step: int) -> None:
79
+ with open(os.path.join(self.config["trainer"]["save_checkpoint_path"], "experiment_log.jsonl"), "a") as f:
80
+ f.write(json.dumps({"step": step, **unflatten_dict(data)}) + "\n")
81
+
82
+
83
+ class MlflowLogger(Logger):
84
+ def __init__(self, config: dict[str, Any]) -> None:
85
+ mlflow.start_run(run_name=config["trainer"]["experiment_name"])
86
+ mlflow.log_params(flatten_dict(config))
87
+
88
+ def log(self, data: dict[str, Any], step: int) -> None:
89
+ mlflow.log_metrics(metrics=data, step=step)
90
+
91
+
92
+ class SwanlabLogger(Logger):
93
+ def __init__(self, config: dict[str, Any]) -> None:
94
+ swanlab_key = os.getenv("SWANLAB_API_KEY")
95
+ swanlab_dir = os.getenv("SWANLAB_DIR", "swanlab_log")
96
+ swanlab_mode = os.getenv("SWANLAB_MODE", "cloud")
97
+ if swanlab_key:
98
+ swanlab.login(swanlab_key)
99
+
100
+ swanlab.init(
101
+ project=config["trainer"]["project_name"],
102
+ experiment_name=config["trainer"]["experiment_name"],
103
+ config={"UPPERFRAMEWORK": "EasyR1", "FRAMEWORK": "veRL", **config},
104
+ logdir=swanlab_dir,
105
+ mode=swanlab_mode,
106
+ )
107
+
108
+ def log(self, data: dict[str, Any], step: int) -> None:
109
+ swanlab.log(data=data, step=step)
110
+
111
+ def finish(self) -> None:
112
+ swanlab.finish()
113
+
114
+
115
+ class TensorBoardLogger(Logger):
116
+ def __init__(self, config: dict[str, Any]) -> None:
117
+ tensorboard_dir = os.getenv("TENSORBOARD_DIR", "tensorboard_log")
118
+ tensorboard_dir = os.path.join(
119
+ tensorboard_dir, config["trainer"]["project_name"], config["trainer"]["experiment_name"]
120
+ )
121
+ os.makedirs(tensorboard_dir, exist_ok=True)
122
+ print(f"Saving tensorboard log to {tensorboard_dir}.")
123
+ self.writer = SummaryWriter(tensorboard_dir)
124
+ config_dict = {}
125
+ for key, value in flatten_dict(config).items():
126
+ if isinstance(value, (int, float, str, bool, torch.Tensor)):
127
+ config_dict[key] = value
128
+ else:
129
+ config_dict[key] = str(value)
130
+
131
+ self.writer.add_hparams(hparam_dict=config_dict, metric_dict={"placeholder": 0})
132
+
133
+ def log(self, data: dict[str, Any], step: int) -> None:
134
+ for key, value in data.items():
135
+ self.writer.add_scalar(key, value, step)
136
+
137
+ def finish(self):
138
+ self.writer.close()
139
+
140
+
141
+ class WandbLogger(Logger):
142
+ def __init__(self, config: dict[str, Any]) -> None:
143
+ wandb.init(
144
+ project=config["trainer"]["project_name"],
145
+ name=config["trainer"]["experiment_name"],
146
+ config=config,
147
+ )
148
+
149
+ def log(self, data: dict[str, Any], step: int) -> None:
150
+ wandb.log(data=data, step=step)
151
+
152
+ def finish(self) -> None:
153
+ wandb.finish()
154
+
155
+
156
+ LOGGERS = {
157
+ "console": ConsoleLogger,
158
+ "file": FileLogger,
159
+ "mlflow": MlflowLogger,
160
+ "swanlab": SwanlabLogger,
161
+ "tensorboard": TensorBoardLogger,
162
+ "wandb": WandbLogger,
163
+ }
164
+
165
+
166
+ class Tracker:
167
+ def __init__(self, loggers: Union[str, list[str]] = "console", config: Optional[dict[str, Any]] = None):
168
+ if isinstance(loggers, str):
169
+ loggers = [loggers]
170
+
171
+ self.loggers: list[Logger] = []
172
+ for logger in loggers:
173
+ if logger not in LOGGERS:
174
+ raise ValueError(f"{logger} is not supported.")
175
+
176
+ self.loggers.append(LOGGERS[logger](config))
177
+
178
+ self.gen_logger = AggregateGenerationsLogger(loggers, config)
179
+
180
+ def log(self, data: dict[str, Any], step: int) -> None:
181
+ for logger in self.loggers:
182
+ logger.log(data=data, step=step)
183
+
184
+ def log_generation(self, samples: list[tuple[str, str, str, float]], step: int) -> None:
185
+ self.gen_logger.log(samples, step)
186
+
187
+ def __del__(self):
188
+ for logger in self.loggers:
189
+ logger.finish()
EasyR1/verl/workers/sharding_manager/fsdp_ulysses.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Contains a resharding manager that binds weights from FSDP zero3 to XPerfGPT
16
+ """
17
+
18
+ from torch.distributed.device_mesh import DeviceMesh
19
+
20
+ from ...protocol import DataProto, all_gather_data_proto
21
+ from ...utils.ulysses import get_ulysses_sequence_parallel_group, set_ulysses_sequence_parallel_group
22
+ from .base import BaseShardingManager
23
+
24
+
25
+ class FSDPUlyssesShardingManager(BaseShardingManager):
26
+ """
27
+ Sharding manager to support data resharding when using FSDP + Ulysses
28
+ """
29
+
30
+ def __init__(self, device_mesh: DeviceMesh):
31
+ super().__init__()
32
+ self.device_mesh = device_mesh
33
+
34
+ def __enter__(self):
35
+ if self.device_mesh is not None:
36
+ self.prev_sp_group = get_ulysses_sequence_parallel_group()
37
+ set_ulysses_sequence_parallel_group(self.device_mesh["sp"].get_group())
38
+
39
+ def __exit__(self, exc_type, exc_value, traceback):
40
+ if self.device_mesh is not None:
41
+ set_ulysses_sequence_parallel_group(self.prev_sp_group)
42
+
43
+ def preprocess_data(self, data: DataProto) -> DataProto:
44
+ """
45
+ AllGather data from sp region
46
+ This is because the data is first sharded along the FSDP dimension as we utilize the DP_COMPUTE
47
+ In Ulysses, we need to make sure the same data is used across a SP group
48
+ """
49
+ if self.device_mesh is not None:
50
+ sp_size = self.device_mesh["sp"].size()
51
+ sp_group = self.device_mesh["sp"].get_group()
52
+ all_gather_data_proto(data, size=sp_size, group=sp_group)
53
+
54
+ return data
55
+
56
+ def postprocess_data(self, data: DataProto) -> DataProto:
57
+ """
58
+ Split the data to follow FSDP partition
59
+ """
60
+ if self.device_mesh is not None:
61
+ sp_size = self.device_mesh["sp"].size()
62
+ sp_rank = self.device_mesh["sp"].get_local_rank()
63
+ data = data.chunk(chunks=sp_size)[sp_rank]
64
+
65
+ return data
images_part00.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c384c7345087dbbad0d7a8aa71ec24e821765d390ed4316fac2f6cc35ee5e0fc
3
+ size 1053952000
paper_conclusion_rl_test.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:01e0804d334b228793d6744664f946861681ee8ebaa4359e7e2f72505bf699b5
3
+ size 21618420
paper_conclusion_rl_train.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:97843c330a8f589ee97c392ba48e26415e5cf81ec420259e386723545ee1fc3f
3
+ size 85606295