|
| 1 | +"""Create a inference job with openai model and poll its results""" |
| 2 | + |
| 3 | +import json |
| 4 | +import logging |
| 5 | +import os |
| 6 | +import random |
| 7 | +import time |
| 8 | +from typing import Dict |
| 9 | + |
| 10 | +from dotenv import load_dotenv |
| 11 | + |
| 12 | +from openweights import OpenWeights |
| 13 | +import openweights.jobs.inference |
| 14 | + |
| 15 | + |
| 16 | +def run_inference_job_and_get_outputs( |
| 17 | + filepath_conversations: str, |
| 18 | + model_to_evaluate: str, |
| 19 | + wait_for_completion: bool = False, |
| 20 | + display_log_file: bool = False, |
| 21 | + n_examples_to_log: int = 0, |
| 22 | + inference_hyperparameters: Dict = None, |
| 23 | +): |
| 24 | + load_dotenv() |
| 25 | + client = OpenWeights() |
| 26 | + |
| 27 | + # Upload inference file |
| 28 | + with open(filepath_conversations, "rb") as file: |
| 29 | + file = client.files.create(file, purpose="conversations") |
| 30 | + file_id = file["id"] |
| 31 | + |
| 32 | + keys_to_rm = [ |
| 33 | + "learning_rate", |
| 34 | + "per_device_train_batch_size", |
| 35 | + "gradient_accumulation_steps", |
| 36 | + "max_seq_length", |
| 37 | + "load_in_4bit", |
| 38 | + "split", |
| 39 | + ] |
| 40 | + for key in keys_to_rm: |
| 41 | + if key in inference_hyperparameters: |
| 42 | + del inference_hyperparameters[key] |
| 43 | + |
| 44 | + # Create an inference job |
| 45 | + logging.info( |
| 46 | + f"Running inference for {model_to_evaluate} with parameters: {json.dumps(inference_hyperparameters, indent=4)}" |
| 47 | + ) |
| 48 | + job = client.inference.create( |
| 49 | + model=model_to_evaluate, |
| 50 | + input_file_id=file_id, |
| 51 | + **inference_hyperparameters, |
| 52 | + ) |
| 53 | + |
| 54 | + if isinstance(job, dict): |
| 55 | + if "results" in job: # Completed OpenAI jobs |
| 56 | + output = job["results"] |
| 57 | + logging.info(f"Returning loaded outputs with length {len(output)}") |
| 58 | + if n_examples_to_log > 0: |
| 59 | + logging.info(f"Logging {n_examples_to_log} random outputs:") |
| 60 | + random_state = random.getstate() |
| 61 | + for i in random.sample( |
| 62 | + range(len(output)), min(n_examples_to_log, len(output)) |
| 63 | + ): |
| 64 | + logging.info(json.dumps(output[i], indent=4)) |
| 65 | + random.setstate(random_state) |
| 66 | + elif "batch_job_info" in job: # Failed or running OpenAI batch jobs |
| 67 | + logging.info(f"Got batch job: {json.dumps(job, indent=4)}") |
| 68 | + logging.info(f"Retry when the OpenAI batch job is complete...") |
| 69 | + return None |
| 70 | + else: |
| 71 | + raise ValueError(f"Unknown job type: {type(job)}") |
| 72 | + else: # Regular OpenWeigths Jobs |
| 73 | + logging.info(job) |
| 74 | + |
| 75 | + # Poll job status |
| 76 | + current_status = job["status"] |
| 77 | + while True: |
| 78 | + job = client.jobs.retrieve(job["id"]) |
| 79 | + if job["status"] != current_status: |
| 80 | + # logging.info(job) |
| 81 | + current_status = job["status"] |
| 82 | + if job["status"] in ["completed", "failed", "canceled"]: |
| 83 | + break |
| 84 | + if not wait_for_completion: |
| 85 | + break |
| 86 | + time.sleep(5) |
| 87 | + |
| 88 | + if not wait_for_completion and job["status"] != "completed": |
| 89 | + logging.info( |
| 90 | + f"Job {job['id']} did not complete, current status: {job['status']}" |
| 91 | + ) |
| 92 | + return None |
| 93 | + |
| 94 | + # Get log file: |
| 95 | + if display_log_file: |
| 96 | + runs = client.runs.list(job_id=job["id"]) |
| 97 | + for run in runs: |
| 98 | + print(run) |
| 99 | + if run["log_file"]: |
| 100 | + log = client.files.content(run["log_file"]).decode("utf-8") |
| 101 | + print(log) |
| 102 | + print("---") |
| 103 | + |
| 104 | + # Get output |
| 105 | + job = client.jobs.retrieve(job["id"]) |
| 106 | + output_file_id = job["outputs"]["file"] |
| 107 | + output = client.files.content(output_file_id).decode("utf-8") |
| 108 | + output = [json.loads(line) for line in output.splitlines() if line.strip()] |
| 109 | + |
| 110 | + return output |
| 111 | + |
| 112 | + |
| 113 | +if __name__ == "__main__": |
| 114 | + logging.basicConfig(level=logging.INFO) |
| 115 | + |
| 116 | + output = run_inference_job_and_get_outputs( |
| 117 | + filepath_conversations=os.path.join( |
| 118 | + os.path.dirname(__file__), "../tests/inference_dataset_with_prefill.jsonl" |
| 119 | + ), |
| 120 | + model_to_evaluate="openai/gpt-4.1-mini", |
| 121 | + inference_hyperparameters={ |
| 122 | + "max_tokens": 1000, |
| 123 | + "temperature": 0.8, |
| 124 | + "max_model_len": 2048, |
| 125 | + "n_completions_per_prompt": 1, |
| 126 | + "use_batch": False, |
| 127 | + }, |
| 128 | + n_examples_to_log=1, |
| 129 | + ) |
| 130 | + print("parallel output:", output) |
| 131 | + |
| 132 | + output = run_inference_job_and_get_outputs( |
| 133 | + filepath_conversations=os.path.join( |
| 134 | + os.path.dirname(__file__), "../tests/inference_dataset_with_prefill.jsonl" |
| 135 | + ), |
| 136 | + model_to_evaluate="openai/gpt-4.1-mini", |
| 137 | + inference_hyperparameters={ |
| 138 | + "max_tokens": 1000, |
| 139 | + "temperature": 0.8, |
| 140 | + "max_model_len": 2048, |
| 141 | + "n_completions_per_prompt": 1, |
| 142 | + "use_batch": True, |
| 143 | + }, |
| 144 | + n_examples_to_log=1, |
| 145 | + ) |
| 146 | + print("batch output:", output) |
0 commit comments