judgeval 0.0.11__py3-none-any.whl → 0.22.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of judgeval might be problematic. Click here for more details.

Files changed (171) hide show
  1. judgeval/__init__.py +177 -12
  2. judgeval/api/__init__.py +519 -0
  3. judgeval/api/api_types.py +407 -0
  4. judgeval/cli.py +79 -0
  5. judgeval/constants.py +76 -47
  6. judgeval/data/__init__.py +3 -3
  7. judgeval/data/evaluation_run.py +125 -0
  8. judgeval/data/example.py +15 -56
  9. judgeval/data/judgment_types.py +450 -0
  10. judgeval/data/result.py +29 -73
  11. judgeval/data/scorer_data.py +29 -62
  12. judgeval/data/scripts/fix_default_factory.py +23 -0
  13. judgeval/data/scripts/openapi_transform.py +123 -0
  14. judgeval/data/trace.py +121 -0
  15. judgeval/dataset/__init__.py +264 -0
  16. judgeval/env.py +52 -0
  17. judgeval/evaluation/__init__.py +344 -0
  18. judgeval/exceptions.py +27 -0
  19. judgeval/integrations/langgraph/__init__.py +13 -0
  20. judgeval/integrations/openlit/__init__.py +50 -0
  21. judgeval/judges/__init__.py +2 -3
  22. judgeval/judges/base_judge.py +2 -3
  23. judgeval/judges/litellm_judge.py +100 -20
  24. judgeval/judges/together_judge.py +101 -20
  25. judgeval/judges/utils.py +20 -24
  26. judgeval/logger.py +62 -0
  27. judgeval/prompt/__init__.py +330 -0
  28. judgeval/scorers/__init__.py +18 -25
  29. judgeval/scorers/agent_scorer.py +17 -0
  30. judgeval/scorers/api_scorer.py +45 -41
  31. judgeval/scorers/base_scorer.py +83 -38
  32. judgeval/scorers/example_scorer.py +17 -0
  33. judgeval/scorers/exceptions.py +1 -0
  34. judgeval/scorers/judgeval_scorers/__init__.py +0 -148
  35. judgeval/scorers/judgeval_scorers/api_scorers/__init__.py +19 -17
  36. judgeval/scorers/judgeval_scorers/api_scorers/answer_correctness.py +13 -19
  37. judgeval/scorers/judgeval_scorers/api_scorers/answer_relevancy.py +12 -19
  38. judgeval/scorers/judgeval_scorers/api_scorers/faithfulness.py +13 -19
  39. judgeval/scorers/judgeval_scorers/api_scorers/instruction_adherence.py +15 -0
  40. judgeval/scorers/judgeval_scorers/api_scorers/prompt_scorer.py +327 -0
  41. judgeval/scorers/score.py +77 -306
  42. judgeval/scorers/utils.py +4 -199
  43. judgeval/tracer/__init__.py +1122 -2
  44. judgeval/tracer/constants.py +1 -0
  45. judgeval/tracer/exporters/__init__.py +40 -0
  46. judgeval/tracer/exporters/s3.py +119 -0
  47. judgeval/tracer/exporters/store.py +59 -0
  48. judgeval/tracer/exporters/utils.py +32 -0
  49. judgeval/tracer/keys.py +63 -0
  50. judgeval/tracer/llm/__init__.py +7 -0
  51. judgeval/tracer/llm/config.py +78 -0
  52. judgeval/tracer/llm/constants.py +9 -0
  53. judgeval/tracer/llm/llm_anthropic/__init__.py +3 -0
  54. judgeval/tracer/llm/llm_anthropic/config.py +6 -0
  55. judgeval/tracer/llm/llm_anthropic/messages.py +452 -0
  56. judgeval/tracer/llm/llm_anthropic/messages_stream.py +322 -0
  57. judgeval/tracer/llm/llm_anthropic/wrapper.py +59 -0
  58. judgeval/tracer/llm/llm_google/__init__.py +3 -0
  59. judgeval/tracer/llm/llm_google/config.py +6 -0
  60. judgeval/tracer/llm/llm_google/generate_content.py +127 -0
  61. judgeval/tracer/llm/llm_google/wrapper.py +30 -0
  62. judgeval/tracer/llm/llm_openai/__init__.py +3 -0
  63. judgeval/tracer/llm/llm_openai/beta_chat_completions.py +216 -0
  64. judgeval/tracer/llm/llm_openai/chat_completions.py +501 -0
  65. judgeval/tracer/llm/llm_openai/config.py +6 -0
  66. judgeval/tracer/llm/llm_openai/responses.py +506 -0
  67. judgeval/tracer/llm/llm_openai/utils.py +42 -0
  68. judgeval/tracer/llm/llm_openai/wrapper.py +63 -0
  69. judgeval/tracer/llm/llm_together/__init__.py +3 -0
  70. judgeval/tracer/llm/llm_together/chat_completions.py +406 -0
  71. judgeval/tracer/llm/llm_together/config.py +6 -0
  72. judgeval/tracer/llm/llm_together/wrapper.py +52 -0
  73. judgeval/tracer/llm/providers.py +19 -0
  74. judgeval/tracer/managers.py +167 -0
  75. judgeval/tracer/processors/__init__.py +220 -0
  76. judgeval/tracer/utils.py +19 -0
  77. judgeval/trainer/__init__.py +14 -0
  78. judgeval/trainer/base_trainer.py +122 -0
  79. judgeval/trainer/config.py +128 -0
  80. judgeval/trainer/console.py +144 -0
  81. judgeval/trainer/fireworks_trainer.py +396 -0
  82. judgeval/trainer/trainable_model.py +243 -0
  83. judgeval/trainer/trainer.py +70 -0
  84. judgeval/utils/async_utils.py +39 -0
  85. judgeval/utils/decorators/__init__.py +0 -0
  86. judgeval/utils/decorators/dont_throw.py +37 -0
  87. judgeval/utils/decorators/use_once.py +13 -0
  88. judgeval/utils/file_utils.py +97 -0
  89. judgeval/utils/guards.py +36 -0
  90. judgeval/utils/meta.py +27 -0
  91. judgeval/utils/project.py +15 -0
  92. judgeval/utils/serialize.py +253 -0
  93. judgeval/utils/testing.py +70 -0
  94. judgeval/utils/url.py +10 -0
  95. judgeval/utils/version_check.py +28 -0
  96. judgeval/utils/wrappers/README.md +3 -0
  97. judgeval/utils/wrappers/__init__.py +15 -0
  98. judgeval/utils/wrappers/immutable_wrap_async.py +74 -0
  99. judgeval/utils/wrappers/immutable_wrap_async_iterator.py +84 -0
  100. judgeval/utils/wrappers/immutable_wrap_sync.py +66 -0
  101. judgeval/utils/wrappers/immutable_wrap_sync_iterator.py +84 -0
  102. judgeval/utils/wrappers/mutable_wrap_async.py +67 -0
  103. judgeval/utils/wrappers/mutable_wrap_sync.py +67 -0
  104. judgeval/utils/wrappers/py.typed +0 -0
  105. judgeval/utils/wrappers/utils.py +35 -0
  106. judgeval/version.py +5 -0
  107. judgeval/warnings.py +4 -0
  108. judgeval-0.22.2.dist-info/METADATA +265 -0
  109. judgeval-0.22.2.dist-info/RECORD +112 -0
  110. judgeval-0.22.2.dist-info/entry_points.txt +2 -0
  111. judgeval/clients.py +0 -39
  112. judgeval/common/__init__.py +0 -8
  113. judgeval/common/exceptions.py +0 -28
  114. judgeval/common/logger.py +0 -189
  115. judgeval/common/tracer.py +0 -798
  116. judgeval/common/utils.py +0 -763
  117. judgeval/data/api_example.py +0 -111
  118. judgeval/data/datasets/__init__.py +0 -5
  119. judgeval/data/datasets/dataset.py +0 -286
  120. judgeval/data/datasets/eval_dataset_client.py +0 -193
  121. judgeval/data/datasets/ground_truth.py +0 -54
  122. judgeval/data/datasets/utils.py +0 -74
  123. judgeval/evaluation_run.py +0 -132
  124. judgeval/judges/mixture_of_judges.py +0 -248
  125. judgeval/judgment_client.py +0 -354
  126. judgeval/run_evaluation.py +0 -439
  127. judgeval/scorers/judgeval_scorer.py +0 -140
  128. judgeval/scorers/judgeval_scorers/api_scorers/contextual_precision.py +0 -19
  129. judgeval/scorers/judgeval_scorers/api_scorers/contextual_recall.py +0 -19
  130. judgeval/scorers/judgeval_scorers/api_scorers/contextual_relevancy.py +0 -22
  131. judgeval/scorers/judgeval_scorers/api_scorers/hallucination.py +0 -19
  132. judgeval/scorers/judgeval_scorers/api_scorers/json_correctness.py +0 -32
  133. judgeval/scorers/judgeval_scorers/api_scorers/summarization.py +0 -20
  134. judgeval/scorers/judgeval_scorers/api_scorers/tool_correctness.py +0 -19
  135. judgeval/scorers/judgeval_scorers/classifiers/__init__.py +0 -3
  136. judgeval/scorers/judgeval_scorers/classifiers/text2sql/__init__.py +0 -3
  137. judgeval/scorers/judgeval_scorers/classifiers/text2sql/text2sql_scorer.py +0 -54
  138. judgeval/scorers/judgeval_scorers/local_implementations/__init__.py +0 -24
  139. judgeval/scorers/judgeval_scorers/local_implementations/answer_correctness/__init__.py +0 -4
  140. judgeval/scorers/judgeval_scorers/local_implementations/answer_correctness/answer_correctness_scorer.py +0 -277
  141. judgeval/scorers/judgeval_scorers/local_implementations/answer_correctness/prompts.py +0 -169
  142. judgeval/scorers/judgeval_scorers/local_implementations/answer_relevancy/__init__.py +0 -4
  143. judgeval/scorers/judgeval_scorers/local_implementations/answer_relevancy/answer_relevancy_scorer.py +0 -298
  144. judgeval/scorers/judgeval_scorers/local_implementations/answer_relevancy/prompts.py +0 -174
  145. judgeval/scorers/judgeval_scorers/local_implementations/contextual_precision/__init__.py +0 -3
  146. judgeval/scorers/judgeval_scorers/local_implementations/contextual_precision/contextual_precision_scorer.py +0 -264
  147. judgeval/scorers/judgeval_scorers/local_implementations/contextual_precision/prompts.py +0 -106
  148. judgeval/scorers/judgeval_scorers/local_implementations/contextual_recall/__init__.py +0 -3
  149. judgeval/scorers/judgeval_scorers/local_implementations/contextual_recall/contextual_recall_scorer.py +0 -254
  150. judgeval/scorers/judgeval_scorers/local_implementations/contextual_recall/prompts.py +0 -142
  151. judgeval/scorers/judgeval_scorers/local_implementations/contextual_relevancy/__init__.py +0 -3
  152. judgeval/scorers/judgeval_scorers/local_implementations/contextual_relevancy/contextual_relevancy_scorer.py +0 -245
  153. judgeval/scorers/judgeval_scorers/local_implementations/contextual_relevancy/prompts.py +0 -121
  154. judgeval/scorers/judgeval_scorers/local_implementations/faithfulness/__init__.py +0 -3
  155. judgeval/scorers/judgeval_scorers/local_implementations/faithfulness/faithfulness_scorer.py +0 -325
  156. judgeval/scorers/judgeval_scorers/local_implementations/faithfulness/prompts.py +0 -268
  157. judgeval/scorers/judgeval_scorers/local_implementations/hallucination/__init__.py +0 -3
  158. judgeval/scorers/judgeval_scorers/local_implementations/hallucination/hallucination_scorer.py +0 -263
  159. judgeval/scorers/judgeval_scorers/local_implementations/hallucination/prompts.py +0 -104
  160. judgeval/scorers/judgeval_scorers/local_implementations/json_correctness/__init__.py +0 -5
  161. judgeval/scorers/judgeval_scorers/local_implementations/json_correctness/json_correctness_scorer.py +0 -134
  162. judgeval/scorers/judgeval_scorers/local_implementations/summarization/__init__.py +0 -3
  163. judgeval/scorers/judgeval_scorers/local_implementations/summarization/prompts.py +0 -247
  164. judgeval/scorers/judgeval_scorers/local_implementations/summarization/summarization_scorer.py +0 -550
  165. judgeval/scorers/judgeval_scorers/local_implementations/tool_correctness/__init__.py +0 -3
  166. judgeval/scorers/judgeval_scorers/local_implementations/tool_correctness/tool_correctness_scorer.py +0 -157
  167. judgeval/scorers/prompt_scorer.py +0 -439
  168. judgeval-0.0.11.dist-info/METADATA +0 -36
  169. judgeval-0.0.11.dist-info/RECORD +0 -84
  170. {judgeval-0.0.11.dist-info → judgeval-0.22.2.dist-info}/WHEEL +0 -0
  171. {judgeval-0.0.11.dist-info → judgeval-0.22.2.dist-info}/licenses/LICENSE.md +0 -0
@@ -0,0 +1,396 @@
1
+ import asyncio
2
+ import json
3
+ from typing import Optional, Callable, Any, List, Union, Dict
4
+ from fireworks import Dataset # type: ignore[import-not-found]
5
+ from .config import TrainerConfig, ModelConfig
6
+ from .base_trainer import BaseTrainer
7
+ from .trainable_model import TrainableModel
8
+ from judgeval.tracer import Tracer
9
+ from judgeval.tracer.exporters.store import SpanStore
10
+ from judgeval.tracer.exporters import InMemorySpanExporter
11
+ from judgeval.tracer.keys import AttributeKeys
12
+ from judgeval import JudgmentClient
13
+ from judgeval.scorers import ExampleScorer, ExampleAPIScorerConfig
14
+ from judgeval.data import Example
15
+ from .console import _spinner_progress, _print_progress, _print_progress_update
16
+ from judgeval.exceptions import JudgmentRuntimeError
17
+
18
+
19
+ class FireworksTrainer(BaseTrainer):
20
+ """
21
+ Fireworks AI implementation of the training provider.
22
+
23
+ This trainer uses Fireworks AI's infrastructure for reinforcement learning
24
+ fine-tuning (RFT) of language models.
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ config: TrainerConfig,
30
+ trainable_model: TrainableModel,
31
+ tracer: Tracer,
32
+ project_name: Optional[str] = None,
33
+ ):
34
+ """
35
+ Initialize the FireworksTrainer.
36
+
37
+ Args:
38
+ config: TrainerConfig instance with training parameters
39
+ trainable_model: TrainableModel instance for Fireworks training
40
+ tracer: Tracer for observability
41
+ project_name: Project name for organizing training runs and evaluations
42
+ """
43
+ try:
44
+ super().__init__(config, trainable_model, tracer, project_name)
45
+
46
+ self.judgment_client = JudgmentClient()
47
+ self.span_store = SpanStore()
48
+ self.span_exporter = InMemorySpanExporter(self.span_store)
49
+ except Exception as e:
50
+ raise JudgmentRuntimeError(
51
+ f"Failed to initialize FireworksTrainer: {str(e)}"
52
+ ) from e
53
+
54
+ def _extract_message_history_from_spans(
55
+ self, trace_id: str
56
+ ) -> List[Dict[str, str]]:
57
+ """
58
+ Extract message history from spans in the span store for training purposes.
59
+
60
+ This method processes trace spans to reconstruct the conversation flow,
61
+ extracting messages in chronological order from LLM, user, and tool spans.
62
+
63
+ Args:
64
+ trace_id: The trace ID (32-char hex string) to extract message history from
65
+
66
+ Returns:
67
+ List of message dictionaries with 'role' and 'content' keys
68
+ """
69
+ spans = self.span_store.get_by_trace_id(trace_id)
70
+ if not spans:
71
+ return []
72
+
73
+ messages = []
74
+ first_found = False
75
+
76
+ for span in sorted(spans, key=lambda s: getattr(s, "start_time", 0)):
77
+ span_attributes = span.attributes or {}
78
+ span_type = span_attributes.get(AttributeKeys.JUDGMENT_SPAN_KIND, "span")
79
+
80
+ if (
81
+ not span_attributes.get(AttributeKeys.JUDGMENT_OUTPUT)
82
+ and span_type != "llm"
83
+ ):
84
+ continue
85
+
86
+ if span_type == "llm":
87
+ if not first_found and span_attributes.get(
88
+ AttributeKeys.JUDGMENT_INPUT
89
+ ):
90
+ input_data: Any = span_attributes.get(
91
+ AttributeKeys.JUDGMENT_INPUT, {}
92
+ )
93
+ if isinstance(input_data, dict) and "messages" in input_data:
94
+ input_messages = input_data["messages"]
95
+ if input_messages:
96
+ first_found = True
97
+ for msg in input_messages:
98
+ if (
99
+ isinstance(msg, dict)
100
+ and "role" in msg
101
+ and "content" in msg
102
+ ):
103
+ messages.append(
104
+ {"role": msg["role"], "content": msg["content"]}
105
+ )
106
+
107
+ # Add assistant response from span output
108
+ output = span_attributes.get(AttributeKeys.JUDGMENT_OUTPUT)
109
+ if output is not None:
110
+ content = str(output)
111
+ try:
112
+ parsed = json.loads(content)
113
+ if isinstance(parsed, dict) and "messages" in parsed:
114
+ # Extract the actual assistant message content
115
+ for msg in parsed["messages"]:
116
+ if (
117
+ isinstance(msg, dict)
118
+ and msg.get("role") == "assistant"
119
+ ):
120
+ content = msg.get("content", content)
121
+ break
122
+ except (json.JSONDecodeError, KeyError):
123
+ pass
124
+ messages.append({"role": "assistant", "content": content})
125
+
126
+ elif span_type in ("user", "tool"):
127
+ output = span_attributes.get(AttributeKeys.JUDGMENT_OUTPUT)
128
+ if output is not None:
129
+ content = str(output)
130
+ try:
131
+ parsed = json.loads(content)
132
+ if isinstance(parsed, dict) and "messages" in parsed:
133
+ for msg in parsed["messages"]:
134
+ if isinstance(msg, dict) and msg.get("role") == "user":
135
+ content = msg.get("content", content)
136
+ break
137
+ except (json.JSONDecodeError, KeyError):
138
+ pass
139
+ messages.append({"role": "user", "content": content})
140
+
141
+ return messages
142
+
143
+ async def generate_rollouts_and_rewards(
144
+ self,
145
+ agent_function: Callable[[Any], Any],
146
+ scorers: List[Union[ExampleAPIScorerConfig, ExampleScorer]],
147
+ prompts: List[Any],
148
+ num_prompts_per_step: Optional[int] = None,
149
+ num_generations_per_prompt: Optional[int] = None,
150
+ concurrency: Optional[int] = None,
151
+ ):
152
+ """
153
+ Generate rollouts and compute rewards using the current model snapshot.
154
+ Each sample contains multiple generations for reinforcement learning optimization.
155
+
156
+ Args:
157
+ agent_function: Function/agent to call for generating responses
158
+ scorers: List of scorer objects to evaluate responses
159
+ prompts: List of prompts to use for training
160
+ num_prompts_per_step: Number of prompts to use per step (defaults to config value, limited by prompts list length)
161
+ num_generations_per_prompt: Generations per prompt (defaults to config value)
162
+ concurrency: Concurrency limit (defaults to config value)
163
+
164
+ Returns:
165
+ List of dataset rows containing samples with messages and evaluations
166
+ """
167
+ num_prompts_per_step = min(
168
+ num_prompts_per_step or self.config.num_prompts_per_step, len(prompts)
169
+ )
170
+ num_generations_per_prompt = (
171
+ num_generations_per_prompt or self.config.num_generations_per_prompt
172
+ )
173
+ concurrency = concurrency or self.config.concurrency
174
+
175
+ semaphore = asyncio.Semaphore(concurrency)
176
+
177
+ @self.tracer.observe(span_type="function")
178
+ async def generate_single_response(prompt_id, generation_id):
179
+ async with semaphore:
180
+ prompt_input = prompts[prompt_id]
181
+ response_data = await agent_function(**prompt_input)
182
+ messages = response_data.get("messages", [])
183
+
184
+ current_span = self.tracer.get_current_span()
185
+ trace_id = None
186
+ if current_span and current_span.is_recording():
187
+ # Convert trace_id to hex string per OTEL spec
188
+ trace_id = format(current_span.get_span_context().trace_id, "032x")
189
+
190
+ try:
191
+ if trace_id is not None:
192
+ traced_messages = self._extract_message_history_from_spans(
193
+ trace_id
194
+ )
195
+ if traced_messages:
196
+ messages = traced_messages
197
+ except Exception as e:
198
+ print(f"Warning: Failed to get message history from trace: {e}")
199
+ pass
200
+
201
+ finally:
202
+ if trace_id is not None:
203
+ self.span_store.clear_trace(trace_id)
204
+
205
+ example = Example(
206
+ input=prompt_input,
207
+ messages=messages,
208
+ actual_output=response_data,
209
+ )
210
+
211
+ scoring_results = self.judgment_client.run_evaluation(
212
+ examples=[example],
213
+ scorers=scorers,
214
+ project_name=self.project_name,
215
+ eval_run_name=f"training_step_{self.trainable_model.current_step}_prompt_{prompt_id}_gen_{generation_id}",
216
+ )
217
+
218
+ if scoring_results and scoring_results[0].scorers_data:
219
+ scores = [
220
+ scorer_data.score
221
+ for scorer_data in scoring_results[0].scorers_data
222
+ if scorer_data.score is not None
223
+ ]
224
+ reward = sum(scores) / len(scores) if scores else 0.0
225
+ else:
226
+ reward = 0.0
227
+
228
+ return {
229
+ "prompt_id": prompt_id,
230
+ "generation_id": generation_id,
231
+ "messages": messages,
232
+ "evals": {"score": reward},
233
+ }
234
+
235
+ coros = []
236
+ for prompt_id in range(num_prompts_per_step):
237
+ for generation_id in range(num_generations_per_prompt):
238
+ coro = generate_single_response(prompt_id, generation_id)
239
+ coros.append(coro)
240
+
241
+ with _spinner_progress(f"Generating {len(coros)} rollouts..."):
242
+ num_completed = 0
243
+ results = []
244
+
245
+ for coro in asyncio.as_completed(coros):
246
+ result = await coro
247
+ results.append(result)
248
+ num_completed += 1
249
+
250
+ _print_progress(f"Generated {len(results)} rollouts successfully")
251
+
252
+ dataset_rows = []
253
+ for prompt_id in range(num_prompts_per_step):
254
+ prompt_generations = [r for r in results if r["prompt_id"] == prompt_id]
255
+ sample_generations = [
256
+ {"messages": gen["messages"], "evals": gen["evals"]}
257
+ for gen in prompt_generations
258
+ ]
259
+ dataset_rows.append({"samples": sample_generations})
260
+
261
+ return dataset_rows
262
+
263
+ async def run_reinforcement_learning(
264
+ self,
265
+ agent_function: Callable[[Any], Any],
266
+ scorers: List[Union[ExampleAPIScorerConfig, ExampleScorer]],
267
+ prompts: List[Any],
268
+ ) -> ModelConfig:
269
+ """
270
+ Run the iterative reinforcement learning fine-tuning loop.
271
+
272
+ This method performs multiple steps of reinforcement learning, where each step:
273
+ 1. Advances to the appropriate model snapshot
274
+ 2. Generates rollouts and computes rewards using scorers
275
+ 3. Trains a new model using reinforcement learning
276
+ 4. Waits for training completion
277
+
278
+ Args:
279
+ agent_function: Function/agent to call for generating responses
280
+ scorers: List of scorer objects to evaluate responses
281
+ prompts: List of prompts to use for training
282
+
283
+ Returns:
284
+ ModelConfig: Configuration of the trained model for inference and future training
285
+ """
286
+
287
+ _print_progress("Starting reinforcement learning training")
288
+
289
+ training_params = {
290
+ "num_steps": self.config.num_steps,
291
+ "num_prompts_per_step": self.config.num_prompts_per_step,
292
+ "num_generations_per_prompt": self.config.num_generations_per_prompt,
293
+ "epochs": self.config.epochs,
294
+ "learning_rate": self.config.learning_rate,
295
+ "accelerator_count": self.config.accelerator_count,
296
+ "accelerator_type": self.config.accelerator_type,
297
+ "temperature": self.config.temperature,
298
+ "max_tokens": self.config.max_tokens,
299
+ }
300
+
301
+ start_step = self.trainable_model.current_step
302
+
303
+ for step in range(start_step, self.config.num_steps):
304
+ step_num = step + 1
305
+ _print_progress(
306
+ f"Starting training step {step_num}", step_num, self.config.num_steps
307
+ )
308
+
309
+ self.trainable_model.advance_to_next_step(step)
310
+
311
+ dataset_rows = await self.generate_rollouts_and_rewards(
312
+ agent_function, scorers, prompts
313
+ )
314
+
315
+ with _spinner_progress(
316
+ "Preparing training dataset", step_num, self.config.num_steps
317
+ ):
318
+ dataset = Dataset.from_list(dataset_rows)
319
+ dataset.sync()
320
+
321
+ _print_progress(
322
+ "Starting reinforcement training", step_num, self.config.num_steps
323
+ )
324
+ job = self.trainable_model.perform_reinforcement_step(dataset, step)
325
+
326
+ last_state = None
327
+ with _spinner_progress(
328
+ "Training job in progress", step_num, self.config.num_steps
329
+ ):
330
+ while not job.is_completed:
331
+ job.raise_if_bad_state()
332
+ current_state = job.state
333
+
334
+ if current_state != last_state:
335
+ if current_state in ["uploading", "validating"]:
336
+ _print_progress_update(
337
+ f"Training job: {current_state} data"
338
+ )
339
+ elif current_state == "training":
340
+ _print_progress_update(
341
+ "Training job: model training in progress"
342
+ )
343
+ else:
344
+ _print_progress_update(f"Training job: {current_state}")
345
+ last_state = current_state
346
+
347
+ await asyncio.sleep(10)
348
+ job = job.get()
349
+ if job is None:
350
+ raise JudgmentRuntimeError(
351
+ "Training job was deleted while waiting for completion"
352
+ )
353
+
354
+ _print_progress(
355
+ f"Training completed! New model: {job.output_model}",
356
+ step_num,
357
+ self.config.num_steps,
358
+ )
359
+
360
+ dataset.delete()
361
+
362
+ _print_progress("All training steps completed!")
363
+
364
+ with _spinner_progress("Deploying final trained model"):
365
+ self.trainable_model.advance_to_next_step(self.config.num_steps)
366
+
367
+ return self.trainable_model.get_model_config(training_params)
368
+
369
+ async def train(
370
+ self,
371
+ agent_function: Callable[[Any], Any],
372
+ scorers: List[Union[ExampleAPIScorerConfig, ExampleScorer]],
373
+ prompts: List[Any],
374
+ ) -> ModelConfig:
375
+ """
376
+ Start the reinforcement learning fine-tuning process.
377
+
378
+ This is the main entry point for running the reinforcement learning training.
379
+
380
+ Args:
381
+ agent_function: Function/agent to call for generating responses.
382
+ scorers: List of scorer objects to evaluate responses
383
+ prompts: List of prompts to use for training
384
+
385
+ Returns:
386
+ ModelConfig: Configuration of the trained model for future loading
387
+ """
388
+ try:
389
+ return await self.run_reinforcement_learning(
390
+ agent_function, scorers, prompts
391
+ )
392
+ except JudgmentRuntimeError:
393
+ # Re-raise JudgmentRuntimeError as-is
394
+ raise
395
+ except Exception as e:
396
+ raise JudgmentRuntimeError(f"Training process failed: {str(e)}") from e
@@ -0,0 +1,243 @@
1
+ from fireworks import LLM # type: ignore[import-not-found]
2
+ from .config import TrainerConfig, ModelConfig
3
+ from typing import Optional, Dict, Any, Callable
4
+ from .console import _model_spinner_progress, _print_model_progress
5
+ from judgeval.exceptions import JudgmentRuntimeError
6
+
7
+
8
+ class TrainableModel:
9
+ """
10
+ A wrapper class for managing model snapshots during training.
11
+
12
+ This class automatically handles model snapshot creation and management
13
+ during the RFT (Reinforcement Fine-Tuning) process,
14
+ abstracting away manual snapshot management from users.
15
+ """
16
+
17
+ config: TrainerConfig
18
+ current_step: int
19
+ _current_model: LLM
20
+ _tracer_wrapper_func: Optional[Callable]
21
+ _base_model: LLM
22
+
23
+ def __init__(self, config: TrainerConfig):
24
+ """
25
+ Initialize the TrainableModel.
26
+
27
+ Args:
28
+ config: TrainerConfig instance with model configuration
29
+ """
30
+ try:
31
+ self.config = config
32
+ self.current_step = 0
33
+ self._tracer_wrapper_func = None
34
+
35
+ self._base_model = self._create_base_model()
36
+ self._current_model = self._base_model
37
+ except Exception as e:
38
+ raise JudgmentRuntimeError(
39
+ f"Failed to initialize TrainableModel: {str(e)}"
40
+ ) from e
41
+
42
+ @classmethod
43
+ def from_model_config(cls, model_config: ModelConfig) -> "TrainableModel":
44
+ """
45
+ Create a TrainableModel from a saved ModelConfig.
46
+
47
+ Args:
48
+ model_config: ModelConfig instance with saved model state
49
+
50
+ Returns:
51
+ TrainableModel instance configured to use the saved model
52
+ """
53
+ # Create a TrainerConfig from the ModelConfig
54
+ trainer_config = TrainerConfig(
55
+ base_model_name=model_config.base_model_name,
56
+ deployment_id=model_config.deployment_id,
57
+ user_id=model_config.user_id,
58
+ model_id=model_config.model_id,
59
+ enable_addons=model_config.enable_addons,
60
+ )
61
+
62
+ instance = cls(trainer_config)
63
+ instance.current_step = model_config.current_step
64
+
65
+ if model_config.is_trained and model_config.current_model_name:
66
+ instance._load_trained_model(model_config.current_model_name)
67
+
68
+ return instance
69
+
70
+ def _create_base_model(self):
71
+ """Create and configure the base model."""
72
+ try:
73
+ with _model_spinner_progress(
74
+ "Creating and deploying base model..."
75
+ ) as update_progress:
76
+ update_progress("Creating base model instance...")
77
+ base_model = LLM(
78
+ model=self.config.base_model_name,
79
+ deployment_type="on-demand",
80
+ id=self.config.deployment_id,
81
+ enable_addons=self.config.enable_addons,
82
+ )
83
+ update_progress("Applying deployment configuration...")
84
+ base_model.apply()
85
+ _print_model_progress("Base model deployment ready")
86
+ return base_model
87
+ except Exception as e:
88
+ raise JudgmentRuntimeError(
89
+ f"Failed to create and deploy base model '{self.config.base_model_name}': {str(e)}"
90
+ ) from e
91
+
92
+ def _load_trained_model(self, model_name: str):
93
+ """Load a trained model by name."""
94
+ try:
95
+ with _model_spinner_progress(
96
+ f"Loading and deploying trained model: {model_name}"
97
+ ) as update_progress:
98
+ update_progress("Creating trained model instance...")
99
+ self._current_model = LLM(
100
+ model=model_name,
101
+ deployment_type="on-demand-lora",
102
+ base_id=self.config.deployment_id,
103
+ )
104
+ update_progress("Applying deployment configuration...")
105
+ self._current_model.apply()
106
+ _print_model_progress("Trained model deployment ready")
107
+
108
+ if self._tracer_wrapper_func:
109
+ self._tracer_wrapper_func(self._current_model)
110
+ except Exception as e:
111
+ raise JudgmentRuntimeError(
112
+ f"Failed to load and deploy trained model '{model_name}': {str(e)}"
113
+ ) from e
114
+
115
+ def get_current_model(self):
116
+ return self._current_model
117
+
118
+ @property
119
+ def chat(self):
120
+ """OpenAI-compatible chat interface."""
121
+ return self._current_model.chat
122
+
123
+ @property
124
+ def completions(self):
125
+ """OpenAI-compatible completions interface."""
126
+ return self._current_model.completions
127
+
128
+ def advance_to_next_step(self, step: int):
129
+ """
130
+ Advance to the next training step and update the current model snapshot.
131
+
132
+ Args:
133
+ step: The current training step number
134
+ """
135
+ try:
136
+ self.current_step = step
137
+
138
+ if step == 0:
139
+ self._current_model = self._base_model
140
+ else:
141
+ model_name = f"accounts/{self.config.user_id}/models/{self.config.model_id}-v{step}"
142
+ with _model_spinner_progress(
143
+ f"Creating and deploying model snapshot: {model_name}"
144
+ ) as update_progress:
145
+ update_progress("Creating model snapshot instance...")
146
+ self._current_model = LLM(
147
+ model=model_name,
148
+ deployment_type="on-demand-lora",
149
+ base_id=self.config.deployment_id,
150
+ )
151
+ update_progress("Applying deployment configuration...")
152
+ self._current_model.apply()
153
+ _print_model_progress("Model snapshot deployment ready")
154
+
155
+ if self._tracer_wrapper_func:
156
+ self._tracer_wrapper_func(self._current_model)
157
+ except Exception as e:
158
+ raise JudgmentRuntimeError(
159
+ f"Failed to advance to training step {step}: {str(e)}"
160
+ ) from e
161
+
162
+ def perform_reinforcement_step(self, dataset, step: int):
163
+ """
164
+ Perform a reinforcement learning step using the current model.
165
+
166
+ Args:
167
+ dataset: Training dataset for the reinforcement step
168
+ step: Current step number for output model naming
169
+
170
+ Returns:
171
+ Training job object
172
+ """
173
+ try:
174
+ model_name = f"{self.config.model_id}-v{step + 1}"
175
+ return self._current_model.reinforcement_step(
176
+ dataset=dataset,
177
+ output_model=model_name,
178
+ epochs=self.config.epochs,
179
+ learning_rate=self.config.learning_rate,
180
+ accelerator_count=self.config.accelerator_count,
181
+ accelerator_type=self.config.accelerator_type,
182
+ )
183
+ except Exception as e:
184
+ raise JudgmentRuntimeError(
185
+ f"Failed to start reinforcement learning step {step + 1}: {str(e)}"
186
+ ) from e
187
+
188
+ def get_model_config(
189
+ self, training_params: Optional[Dict[str, Any]] = None
190
+ ) -> ModelConfig:
191
+ """
192
+ Get the current model configuration for persistence.
193
+
194
+ Args:
195
+ training_params: Optional training parameters to include in config
196
+
197
+ Returns:
198
+ ModelConfig instance with current model state
199
+ """
200
+ current_model_name = None
201
+ is_trained = False
202
+
203
+ if self.current_step > 0:
204
+ current_model_name = f"accounts/{self.config.user_id}/models/{self.config.model_id}-v{self.current_step}"
205
+ is_trained = True
206
+
207
+ return ModelConfig(
208
+ base_model_name=self.config.base_model_name,
209
+ deployment_id=self.config.deployment_id,
210
+ user_id=self.config.user_id,
211
+ model_id=self.config.model_id,
212
+ enable_addons=self.config.enable_addons,
213
+ current_step=self.current_step,
214
+ total_steps=self.config.num_steps,
215
+ current_model_name=current_model_name,
216
+ is_trained=is_trained,
217
+ training_params=training_params,
218
+ )
219
+
220
+ def save_model_config(
221
+ self, filepath: str, training_params: Optional[Dict[str, Any]] = None
222
+ ):
223
+ """
224
+ Save the current model configuration to a file.
225
+
226
+ Args:
227
+ filepath: Path to save the configuration file
228
+ training_params: Optional training parameters to include in config
229
+ """
230
+ model_config = self.get_model_config(training_params)
231
+ model_config.save_to_file(filepath)
232
+
233
+ def _register_tracer_wrapper(self, wrapper_func: Callable):
234
+ """
235
+ Register a tracer wrapper function to be reapplied when models change.
236
+
237
+ This is called internally by the tracer's wrap() function to ensure
238
+ that new model instances created during training are automatically wrapped.
239
+
240
+ Args:
241
+ wrapper_func: Function that wraps a model instance with tracing
242
+ """
243
+ self._tracer_wrapper_func = wrapper_func