464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696 | class SweAgentGenerator(SkyRLGymGenerator):
"""Customized SkyRLGymGenerator for SWE-Agent."""
def __init__(
self,
generator_cfg: DictConfig,
skyrl_gym_cfg: DictConfig,
inference_engine_client: InferenceEngineClient,
tokenizer,
model_name: str,
):
# Call parent constructor first
super().__init__(generator_cfg, skyrl_gym_cfg, inference_engine_client, tokenizer, model_name)
self.http_server_inference_engine_client_host = generator_cfg.get(
"http_server_inference_engine_client_host", "127.0.0.1"
)
self.http_server_inference_engine_client_port = generator_cfg.get(
"http_server_inference_engine_client_port", 8000
)
self.base_url = (
f"http://{self.http_server_inference_engine_client_host}:{self.http_server_inference_engine_client_port}"
)
self.generator_cfg = generator_cfg
cli_cfg = self.generator_cfg.sweagent
# # turn cli_cfg into args
if hasattr(cli_cfg, "to_container"):
cli_cfg = cli_cfg.to_container(resolve=True)
flat_cfg = flatten_dict(cli_cfg)
args = []
for key, value in flat_cfg.items():
args.append(f"--{key}")
args.append(str(value))
self.sweagent_config = BasicCLI(RunBatchConfig, help_text='s').get_config(args)
self.tokenizer = tokenizer
self.model_name = model_name
self.litellm_model_name = "openai/" + self.model_name
if self.generator_cfg.chat_template.name_or_path is not None:
raise NotImplementedError("SweAgentGenerator doesn't support custom chat template")
async def minisweagent_agent_loop(
self,
sweagent_config: DictConfig,
instance: BatchInstance,
prompt: ConversationType,
env_extras: Dict[str, Any],
max_tokens: int,
max_input_length: int,
sampling_params: Dict[str, Any],
trajectory_id: TrajectoryID,
batch_metadata: BatchMetadata,
) -> Tuple[List[int], float, str, List[int], List[int], Optional[List[int]]]:
"""
The rollout inner loop for mini-swe-agent. It cakls the init_and_run_container_remote or init_and_run_sb_remote based on the env_type in sweagent_config.
Attributes:
sweagent_config: The sweagent configuration. RunBatchConfig object.
instance: The BatchInstance to run.
prompt: The input prompt. Deprecated. Not used.
env_extras: Extra environment information.
max_tokens: The maximum number of tokens to generate.
max_input_length: The maximum input length.
sampling_params: The sampling parameters to use for the model.
trajectory_id: The trajectory ID. Deprecated. Not used.
batch_metadata: The batch metadata.
"""
# sweagent_config = yaml.safe_load(get_config_path(self.generator_cfg.miniswe_config_path).read_text())
# NOTE (sumanthrh): Input `prompt` is not used here because mini-swe-agent uses a similar entry from the `instance` obj
if sweagent_config.env_type=='sandbox':
ref = init_and_run_sb_remote.remote(
instance,
self.litellm_model_name,
sweagent_config,
self.generator_cfg,
env_extras["data_source"],
sampling_params,
trajectory_id,
batch_metadata.global_step,
batch_metadata.training_phase,
)
elif sweagent_config.env_type=='docker':
ref = init_and_run_container_remote.remote(
instance,
self.litellm_model_name,
sweagent_config,
self.generator_cfg,
env_extras["data_source"],
sampling_params,
trajectory_id,
batch_metadata.global_step,
batch_metadata.training_phase,
)
else:
raise Exception()
messages, reward, error = await asyncio.to_thread(ray.get, ref)
if not len(messages):
return None, None, None, None, None, None
# TODO (sumanthrh): This is currently hardcoded for SWEBench with 2 initial messages (system and user).
response_messages = messages[2:]
for message in messages[:2]:
assert message["role"] in (
"system",
"user",
), "Expected the first two messages to be system and user messages"
initial_input_ids = self.tokenizer.apply_chat_template(messages[:2], add_generation_prompt=False, tokenize=True)
initial_prompt_length = len(initial_input_ids)
response_ids: List[int] = []
loss_mask: List[int] = []
# We remove trailing `user` messages - this is added by Mini-SWE-Agent to capture the final git diff for the trajectory
last_idx = len(response_messages) - 1
while response_messages[last_idx]["role"] == "user":
last_idx -= 1
if last_idx < 0:
raise ValueError(
"Found no assistant messages. Please ensure that your environment is configured correctly and the `OPENAI_BASE_URL` points to the HTTP server from the inference engine client"
)
response_messages = response_messages[: last_idx + 1]
for message in response_messages:
# Apply chat template and tokenize each message
msg_encoding = encode_messages_subset([message], self.tokenizer)
# Extend response_ids with the tokens
response_ids.extend(msg_encoding)
# Extend loss_mask: 0s for user, 1s for assistant
if message["role"] == "user":
loss_mask.extend([0] * len(msg_encoding))
else: # assistant
loss_mask.extend([1] * len(msg_encoding))
# Extract prompt ids
prompt_ids = initial_input_ids
# Calculate maximum response tokens allowed
max_response_tokens = max_tokens + max_input_length - initial_prompt_length
# Determine stop reason
stop_reason = "complete" # Default for trial completion
if len(response_ids) > max_response_tokens:
stop_reason = "length"
# Truncate to maximum allowed length
response_ids = response_ids[:max_response_tokens]
loss_mask = loss_mask[:max_response_tokens]
return (response_ids, reward, stop_reason, loss_mask, prompt_ids, None)
async def generate(self, input_batch: GeneratorInput) -> GeneratorOutput:
"""
Generate trajectories for the input batch. It call the minisweagent_agent_loop for each instance in the batch concurrently.
Returns outputs in the same order as the input batch.
Attributes:
input_batch: GeneratorInput
Returns:
GeneratorOutput
"""
prompts = input_batch["prompts"]
env_extras = input_batch["env_extras"]
trajectory_ids = input_batch["trajectory_ids"]
batch_metadata = input_batch["batch_metadata"]
max_tokens = self.generator_cfg.sampling_params.max_generate_length
max_input_length = self.generator_cfg.max_input_length
sampling_params = get_sampling_params_for_backend(
self.generator_cfg.backend, self.generator_cfg.sampling_params
)
tasks = []
datasets=[]
for i in range(len(env_extras)):
data_instance = copy.deepcopy(env_extras[i]["instance"])
data_instance['traj_id'] = data_instance['instance_id']+'@'+str(trajectory_ids[i].repetition_id)
data_instance['global_step'] = env_extras[i]['global_step']
datasets.append(data_instance)
instances = self.sweagent_config.instances.get_instance_configs_ds(datasets)
for i in range(len(prompts)):
tasks.append(
self.minisweagent_agent_loop(
self.sweagent_config,
instances[i],
prompts[i],
env_extras[i],
max_tokens=max_tokens,
max_input_length=max_input_length,
sampling_params=sampling_params,
trajectory_id=trajectory_ids[i],
batch_metadata=batch_metadata,
)
)
all_outputs = await asyncio.gather(*tasks)
# Filter out the `None` entries, which means that trajectory generation failed
responses = [output[0] for output in all_outputs if output[0] is not None]
rewards = [output[1] for output in all_outputs if output[0] is not None]
stop_reasons = [output[2] for output in all_outputs if output[0] is not None]
loss_masks = [output[3] for output in all_outputs if output[0] is not None]
prompt_token_ids = [output[4] for output in all_outputs if output[0] is not None]
if not len(responses):
raise ValueError(
"Found no valid responses for this step. This means that generation failed for all trajectories, likely due to errors in environment setup."
)
rollout_metrics = get_rollout_metrics(responses, rewards)
generator_output: GeneratorOutput = {
"prompt_token_ids": prompt_token_ids,
"response_ids": responses,
"rewards": rewards,
"loss_masks": loss_masks,
"stop_reasons": stop_reasons,
"rollout_metrics": rollout_metrics,
"rollout_logprobs": None,
}
return generator_output
|