Spaces:
Sleeping
Sleeping
File size: 8,851 Bytes
3bf8430 7769657 3bf8430 1cbc0f5 3bf8430 1cbc0f5 7769657 1cbc0f5 7769657 1cbc0f5 c4bedee 1cbc0f5 7769657 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 c4bedee 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 c4bedee 3bf8430 c4bedee 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 1cbc0f5 3bf8430 c4bedee 3bf8430 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
"""
RLVE-Gym Environment Implementation.
"""
import os
from typing import Optional, Tuple
import random
from openenv_core.env_server.interfaces import Environment
from models import RlveGymState, RlveGymAction, RlveGymObservation
from server.Gym.environment import VerifiableEnvironment
from server.Gym.parameter_controller import ParameterController
from server.Gym.environments import identifier2environment
from server.Gym.parameter_controllers import identifier2controller
class RlveGymEnvironment(Environment):
"""
Wrap any verifiable environment from RLVE-Gym behind the OpenEnv ``Environment`` API.
"""
def __init__(
self,
environment_identifier: str = None,
difficulty: int = None,
answer_markers: Optional[Tuple[str, str]] = None,
initial_seed: int = None,
):
"""
Initialize the RLVE_Gym environment.
Args:
environment_identifier (str): The environment's identifier. Check server/Gym/environments/__init__.py for detailed usage.
difficulty (int): The difficulty of generated problems.
answer_markers (Tuple[str] of length 2): How the environment extracts the final answer from a model output.
initial_seed (int): The initial seed to use when generating the first problem. Whenever reset() is called, the seed will be incremented by 1.
"""
if environment_identifier is not None :
self.environment_identifier = environment_identifier
else :
self.environment_identifier = os.getenv("RLVEGYM_ENVIRONMENT_IDENTIFIER", default = "Multiplication")
if difficulty is not None :
self.difficulty = difficulty
else :
self.difficulty = int(os.getenv("RLVEGYM_DIFFICULTY", default = "0"))
if answer_markers is not None :
self.answer_markers = answer_markers
else :
self.answer_markers = (os.getenv("RLVEGYM_ANSWER_MARKER_START", default = r"<answer>"), os.getenv("RLVEGYM_ANSWER_MARKER_END", default = r"</answer>"))
if initial_seed is not None :
pass
else :
initial_seed = int(os.getenv("RLVEGYM_INITIAL_SEED", default = "0"))
self._state = RlveGymState(
seed=initial_seed,
problem_input=None,
num_samples=0,
sum_accuracy=0,
)
self.problem = None
def reset(self) -> RlveGymObservation:
"""
Reset the environment.
Returns:
problem_input (Optional[str]): The input of the problem; if it is None, it means that the problem generation has not been run or has failed.
verifier_result (Optional[dict]): Contains reward as the raw reward, accuracy as the 0/1 correctness, and format_score as the 0/1 format correctness; if it is None, it means that the verification has failed.
success (bool): True or False indicates whether the operation succeeded.
message (str): The explanation of success.
reward (Optional[float]): The value is verifier_result["reward"] when verifier_result is not None (otherwise, reward is also None).
"""
if (self.environment_identifier not in identifier2environment) or (
self.environment_identifier not in identifier2controller
):
return RlveGymObservation(
problem_input=None,
verifier_result=None,
success=False,
message="Invalid environment identifier.",
reward=None,
)
if not (isinstance(self.difficulty, int) and self.difficulty >= 0):
return RlveGymObservation(
problem_input=None,
verifier_result=None,
success=False,
message="Difficulty should be a non-negative integer.",
reward=None,
)
if not (isinstance(self._state.seed, int) and self._state.seed >= 0):
return RlveGymObservation(
problem_input=None,
verifier_result=None,
success=False,
message="Seed should be a non-negative integer.",
reward=None,
)
try:
problem: VerifiableEnvironment = identifier2environment[self.environment_identifier](
answer_markers=self.answer_markers
)
except Exception as e:
return RlveGymObservation(
problem_input=None,
verifier_result=None,
success=False,
message=f"Failed to initialize environment: {e}",
reward=None,
)
controller: ParameterController = identifier2controller[self.environment_identifier]()
for _ in range(self.difficulty):
controller.update()
random.seed(self._state.seed)
parameter = random.choice(controller.get_parameter_list())
if problem.generator(seed=self._state.seed, parameter=parameter):
self._state.problem_input = problem.prompt_generator()
self.problem = problem
else:
self._state.problem_input = None
self.problem = None
self._state.seed += 1
self._state.num_samples = self._state.sum_accuracy = 0
if self.problem is not None:
return RlveGymObservation(
problem_input=self._state.problem_input,
verifier_result=None,
success=True,
message="Problem generated successfully.",
reward=None,
)
else:
return RlveGymObservation(
problem_input=None,
verifier_result=None,
success=False,
message="Problem generation failed. Please try decreasing difficulty or changing seed.",
reward=None,
)
def step(self, action: RlveGymAction) -> RlveGymObservation: # type: ignore[override]
"""
Execute a step in the environment by verifying the model output.
Args:
action (RlveGymAction): Contains a single field:
- output (str): The model's output to get verified.
Returns:
problem_input (Optional[str]): The input of the problem; if it is None, it means that the problem generation has not been run or has failed.
verifier_result (Optional[dict]): Contains reward as the raw reward, accuracy as the 0/1 correctness, and format_score as the 0/1 format correctness; if it is None, it means that the verification has failed.
success (bool): True or False indicates whether the operation succeeded.
message (str): The explanation of success.
reward (Optional[float]): The value is verifier_result["reward"] when verifier_result is not None (otherwise, reward is also None).
"""
if self.problem is None:
return RlveGymObservation(
problem_input=None,
verifier_result=None,
success=False,
message="Problem not ready. Please reset the environment.",
reward=None,
)
try:
verifier_result = self.problem.verifier(action.output)
except Exception as e:
return RlveGymObservation(
problem_input=self._state.problem_input,
verifier_result=None,
success=False,
message=f"Verification failed with error: {e}",
reward=None,
)
self._state.num_samples += 1
self._state.sum_accuracy += verifier_result["accuracy"]
return RlveGymObservation(
problem_input=self._state.problem_input,
verifier_result=verifier_result,
success=True,
message="Verification completed.",
reward=verifier_result["reward"],
)
@property
def state(self) -> RlveGymState:
"""
Get the current environment state.
Returns:
seed (int): The seed to use when running reset().
problem_input (Optional[str]): The input of the problem; if it is None, it means that the problem generation has not been run, or it failed.
num_samples (int) and sum_accuracy (int): The statistics of the result of `step(action)` so far for the current problem (the number of outputs sent to the verifier and the number of correct ones).
"""
return self._state
|