-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert_for_training.py
More file actions
201 lines (157 loc) · 6.1 KB
/
convert_for_training.py
File metadata and controls
201 lines (157 loc) · 6.1 KB
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
"""
Convert dataset.jsonl to various fine-tuning formats
Supported formats:
1. Instruction-following (for instruction-tuned models)
2. Conversational (for chat models)
3. Completion (for base models)
"""
import json
from pathlib import Path
from typing import List, Dict, Any
def format_structured_response(response: Dict[str, Any]) -> str:
"""Format the structured response into readable text"""
parts = []
if response.get("facts"):
parts.append("FACTS:")
for fact in response["facts"]:
parts.append(f" • {fact}")
if response.get("uncertainties"):
parts.append("\nUNCERTAINTIES:")
for unc in response["uncertainties"]:
parts.append(f" • {unc}")
if response.get("analysis"):
parts.append("\nANALYSIS:")
for analysis in response["analysis"]:
parts.append(f" • {analysis}")
if response.get("guidance"):
parts.append("\nGUIDANCE:")
for guidance in response["guidance"]:
parts.append(f" • {guidance}")
if "confidence" in response:
parts.append(f"\nConfidence: {response['confidence']:.2f}")
return "\n".join(parts)
def convert_to_instruction_format(sample: Dict[str, Any], role: str = "civilian") -> Dict[str, str]:
"""Convert to instruction-following format (instruction + response)"""
scenario = sample["scenario"]
category = sample["category"]
response = sample["responses"][role]
instruction = f"""You are a crisis response expert. Analyze the following crisis scenario and provide a structured response.
Category: {category}
Scenario:
{scenario}
Provide your analysis with:
- Key facts you can observe
- Uncertainties that need clarification
- Your analysis of the situation
- Actionable guidance
Role: {role.title()}"""
output = format_structured_response(response)
return {
"instruction": instruction,
"output": output,
"category": category,
"role": role
}
def convert_to_conversational_format(sample: Dict[str, Any], role: str = "civilian") -> Dict[str, Any]:
"""Convert to conversational format (messages with roles)"""
scenario = sample["scenario"]
category = sample["category"]
response = sample["responses"][role]
messages = [
{
"role": "system",
"content": f"You are a crisis response expert specializing in {category} scenarios. Provide structured, actionable guidance based on crisis situations."
},
{
"role": "user",
"content": f"Category: {category}\n\nScenario:\n{scenario}\n\nAnalyze this crisis situation and provide guidance. Role: {role.title()}"
},
{
"role": "assistant",
"content": format_structured_response(response)
}
]
return {
"messages": messages,
"category": category,
"role": role
}
def convert_to_completion_format(sample: Dict[str, Any], role: str = "civilian") -> Dict[str, str]:
"""Convert to completion format (prompt + completion)"""
scenario = sample["scenario"]
category = sample["category"]
response = sample["responses"][role]
prompt = f"""Category: {category}
Scenario:
{scenario}
As a {role}, analyze this crisis and provide structured guidance:
"""
completion = format_structured_response(response)
return {
"prompt": prompt,
"completion": completion,
"category": category,
"role": role
}
def convert_dataset(
input_path: Path,
output_path: Path,
format_type: str = "instruction",
role: str = "civilian",
include_both_roles: bool = False
):
"""
Convert dataset to training format
Args:
input_path: Path to dataset.jsonl
output_path: Path to output file
format_type: "instruction", "conversational", or "completion"
role: "civilian" or "first responder"
include_both_roles: If True, create separate examples for each role
"""
samples = []
# Load samples
with open(input_path, "r", encoding="utf-8") as f:
for line in f:
if line.strip():
samples.append(json.loads(line))
converted = []
for sample in samples:
roles_to_process = ["civilian", "first responder"] if include_both_roles else [role]
for r in roles_to_process:
if format_type == "instruction":
converted.append(convert_to_instruction_format(sample, r))
elif format_type == "conversational":
converted.append(convert_to_conversational_format(sample, r))
elif format_type == "completion":
converted.append(convert_to_completion_format(sample, r))
else:
raise ValueError(f"Unknown format: {format_type}")
# Write output
with open(output_path, "w", encoding="utf-8") as f:
for item in converted:
f.write(json.dumps(item, ensure_ascii=False) + "\n")
print(f"Converted {len(samples)} samples to {len(converted)} training examples")
print(f"Format: {format_type}")
print(f"Output: {output_path}")
if __name__ == "__main__":
import typer
app = typer.Typer(help="Convert dataset for fine-tuning")
@app.command()
def convert(
input_file: str = typer.Option("data/dataset.jsonl", help="Input dataset file"),
output_file: str = typer.Option("data/training_data.jsonl", help="Output training file"),
format_type: str = typer.Option("instruction", help="Format: instruction, conversational, or completion"),
role: str = typer.Option("civilian", help="Role: civilian or first_responder"),
both_roles: bool = typer.Option(False, help="Include both roles as separate examples")
):
"""Convert dataset to fine-tuning format"""
convert_dataset(
Path(input_file),
Path(output_file),
format_type=format_type,
role=role.replace("_", " "),
include_both_roles=both_roles
)
if __name__ == "__main__":
app()