|
| 1 | +import asyncio |
| 2 | +import os |
| 3 | +import random |
| 4 | +from itertools import permutations |
| 5 | + |
| 6 | +import art |
| 7 | +import litellm |
| 8 | +from art.serverless.backend import ServerlessBackend |
| 9 | +from art.utils.deploy_model import ( |
| 10 | + LoRADeploymentProvider, |
| 11 | + deploy_model, |
| 12 | +) |
| 13 | +from art.utils.litellm import convert_litellm_choice_to_openai |
| 14 | +from dotenv import load_dotenv |
| 15 | +from litellm.types.utils import Choices, ModelResponse |
| 16 | + |
| 17 | +load_dotenv() |
| 18 | + |
| 19 | + |
| 20 | +async def rollout(model: art.Model, scenario: str, step: int) -> art.Trajectory: |
| 21 | + messages: art.Messages = [ |
| 22 | + { |
| 23 | + "role": "user", |
| 24 | + "content": scenario, |
| 25 | + } |
| 26 | + ] |
| 27 | + response = await litellm.acompletion( |
| 28 | + messages=messages, |
| 29 | + model=f"openai/{model.get_inference_name()}", |
| 30 | + max_tokens=100, |
| 31 | + timeout=100, |
| 32 | + base_url=model.inference_base_url, |
| 33 | + api_key=model.inference_api_key, |
| 34 | + ) |
| 35 | + assert isinstance(response, ModelResponse) |
| 36 | + choice = response.choices[0] |
| 37 | + assert isinstance(choice, Choices) |
| 38 | + content = choice.message.content |
| 39 | + assert isinstance(content, str) |
| 40 | + if content == "yes": |
| 41 | + reward = 0.5 |
| 42 | + elif content == "no": |
| 43 | + reward = 0.75 |
| 44 | + elif content == "maybe": |
| 45 | + reward = 1.0 |
| 46 | + else: |
| 47 | + reward = 0.0 |
| 48 | + return art.Trajectory( |
| 49 | + messages_and_choices=[*messages, convert_litellm_choice_to_openai(choice)], |
| 50 | + reward=reward, |
| 51 | + metrics={"custom_metric": random.random(), "run_step": step}, |
| 52 | + ) |
| 53 | + |
| 54 | + |
| 55 | +async def main() -> None: |
| 56 | + backend = ServerlessBackend( |
| 57 | + base_url="https://api.qa.training.wandb.ai/v1", |
| 58 | + api_key="be47e013c03bd1afc979794cde276bdd421de0f3", |
| 59 | + # api_key="be47e013c03bd1afc979794cde276bdd421de0f3", // production |
| 60 | + ) |
| 61 | + model = art.TrainableModel( |
| 62 | + name="".join(random.choices("abcdefghijklmnopqrstuvwxyz0123456789", k=8)), |
| 63 | + project="yes-no-maybe", |
| 64 | + base_model="Qwen/Qwen2.5-14B-Instruct", |
| 65 | + ) |
| 66 | + await model.register(backend) |
| 67 | + print(f"Created model: {model.name}") |
| 68 | + |
| 69 | + def with_quotes(w: str) -> str: |
| 70 | + return f"'{w}'" |
| 71 | + |
| 72 | + scenarios = [ |
| 73 | + f"{prefix} with {', '.join([with_quotes(w) if use_quotes else w for w in words]) if len(words) == 3 else f'{words[0]}' + (f' or {words[1]}' if len(words) > 1 else '')}" |
| 74 | + for prefix in ["respond", "just respond"] |
| 75 | + for use_quotes in [True, False] |
| 76 | + for words in ( |
| 77 | + list(p) for n in [3, 2] for p in permutations(["yes", "no", "maybe"], n) |
| 78 | + ) |
| 79 | + ] |
| 80 | + random.seed(42) |
| 81 | + random.shuffle(scenarios) |
| 82 | + val_scenarios = scenarios[: len(scenarios) // 2] |
| 83 | + train_scenarios = scenarios[len(scenarios) // 2 :] |
| 84 | + |
| 85 | + has_printed_step_warning = False |
| 86 | + target_steps = 1 # Train for 1 steps |
| 87 | + starting_step = await model.get_step() |
| 88 | + |
| 89 | + for _step in range(starting_step, starting_step + target_steps): |
| 90 | + step = await model.get_step() |
| 91 | + if step != _step and not has_printed_step_warning: |
| 92 | + print(f"Warning: Step mismatch: {step} != {_step}") |
| 93 | + has_printed_step_warning = True |
| 94 | + val_groups = await art.gather_trajectory_groups( |
| 95 | + ( |
| 96 | + art.TrajectoryGroup(rollout(model, scenario, step) for _ in range(8)) |
| 97 | + for scenario in val_scenarios |
| 98 | + ), |
| 99 | + pbar_desc=f"gather(val:{step})", |
| 100 | + ) |
| 101 | + train_groups = await art.gather_trajectory_groups( |
| 102 | + ( |
| 103 | + art.TrajectoryGroup(rollout(model, scenario, step) for _ in range(8)) |
| 104 | + for scenario in train_scenarios |
| 105 | + ), |
| 106 | + pbar_desc=f"gather(train:{step})", |
| 107 | + ) |
| 108 | + await model.log(val_groups) |
| 109 | + await model.train( |
| 110 | + train_groups, |
| 111 | + config=art.TrainConfig(learning_rate=5e-5), |
| 112 | + _config=art.dev.TrainConfig(precalculate_logprobs=True), |
| 113 | + ) |
| 114 | + await model.delete_checkpoints(best_checkpoint_metric="train/reward") |
| 115 | + |
| 116 | + # Download the latest checkpoint to local directory (same folder as this script) |
| 117 | + print("\n" + "=" * 80) |
| 118 | + print("Downloading checkpoint to local directory...") |
| 119 | + print("=" * 80) |
| 120 | + |
| 121 | + script_dir = os.path.dirname(os.path.abspath(__file__)) |
| 122 | + checkpoint_path = await backend._experimental_pull_model_checkpoint( |
| 123 | + model, step="latest", local_path=script_dir, verbose=True |
| 124 | + ) |
| 125 | + |
| 126 | + print(f"\n✓ Checkpoint downloaded to: {checkpoint_path}") |
| 127 | + print("\nFiles in checkpoint directory:") |
| 128 | + print("-" * 80) |
| 129 | + |
| 130 | + # List all files in the checkpoint directory |
| 131 | + for root, dirs, files in os.walk(checkpoint_path): |
| 132 | + level = root.replace(checkpoint_path, "").count(os.sep) |
| 133 | + indent = " " * 2 * level |
| 134 | + print(f"{indent}{os.path.basename(root)}/") |
| 135 | + subindent = " " * 2 * (level + 1) |
| 136 | + for file in files: |
| 137 | + file_size = os.path.getsize(os.path.join(root, file)) |
| 138 | + # Format file size nicely |
| 139 | + if file_size < 1024: |
| 140 | + size_str = f"{file_size}B" |
| 141 | + elif file_size < 1024 * 1024: |
| 142 | + size_str = f"{file_size / 1024:.1f}KB" |
| 143 | + else: |
| 144 | + size_str = f"{file_size / (1024 * 1024):.1f}MB" |
| 145 | + print(f"{subindent}{file} ({size_str})") |
| 146 | + |
| 147 | + # Deploy the checkpoint to Together |
| 148 | + print("\n" + "=" * 80) |
| 149 | + print("Deploying checkpoint to Together...") |
| 150 | + print("=" * 80) |
| 151 | + |
| 152 | + # Extract step number from checkpoint path |
| 153 | + final_step = int(os.path.basename(checkpoint_path)) |
| 154 | + |
| 155 | + deployment_job = await deploy_model( |
| 156 | + deploy_to=LoRADeploymentProvider.TOGETHER, |
| 157 | + model=model, |
| 158 | + checkpoint_path=checkpoint_path, |
| 159 | + step=final_step, |
| 160 | + s3_bucket=None, # Will use default S3 bucket for presigned URL |
| 161 | + verbose=True, |
| 162 | + wait_for_completion=True, |
| 163 | + ) |
| 164 | + |
| 165 | + print(f"\n✓ Deployment complete!") |
| 166 | + print(f" Status: {deployment_job.status}") |
| 167 | + print(f" Job ID: {deployment_job.job_id}") |
| 168 | + print(f" Model Name: {deployment_job.model_name}") |
| 169 | + if deployment_job.failure_reason: |
| 170 | + print(f" Failure Reason: {deployment_job.failure_reason}") |
| 171 | + |
| 172 | + print("\n" + "=" * 80) |
| 173 | + print(f"Training complete! Model: {model.name}") |
| 174 | + print("=" * 80) |
| 175 | + |
| 176 | + |
| 177 | +if __name__ == "__main__": |
| 178 | + asyncio.run(main()) |
0 commit comments