Spaces:
Sleeping
Sleeping
File size: 9,538 Bytes
33d4721 |
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 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
import os
from dataclasses import dataclass
from typing import Optional
import requests
from autotrain import logger
AUTOTRAIN_API = os.environ.get("AUTOTRAIN_API", "https://autotrain-projects-autotrain-advanced.hf.space/")
BACKENDS = {
"spaces-a10g-large": "a10g-large",
"spaces-a10g-small": "a10g-small",
"spaces-a100-large": "a100-large",
"spaces-t4-medium": "t4-medium",
"spaces-t4-small": "t4-small",
"spaces-cpu-upgrade": "cpu-upgrade",
"spaces-cpu-basic": "cpu-basic",
"spaces-l4x1": "l4x1",
"spaces-l4x4": "l4x4",
"spaces-l40sx1": "l40sx1",
"spaces-l40sx4": "l40sx4",
"spaces-l40sx8": "l40sx8",
"spaces-a10g-largex2": "a10g-largex2",
"spaces-a10g-largex4": "a10g-largex4",
}
PARAMS = {}
PARAMS["llm"] = {
"target_modules": "all-linear",
"log": "tensorboard",
"mixed_precision": "fp16",
"quantization": "int4",
"peft": True,
"block_size": 1024,
"epochs": 3,
"padding": "right",
"chat_template": "none",
"max_completion_length": 128,
"distributed_backend": "ddp",
"scheduler": "linear",
"merge_adapter": True,
}
PARAMS["text-classification"] = {
"mixed_precision": "fp16",
"log": "tensorboard",
}
PARAMS["st"] = {
"mixed_precision": "fp16",
"log": "tensorboard",
}
PARAMS["image-classification"] = {
"mixed_precision": "fp16",
"log": "tensorboard",
}
PARAMS["image-object-detection"] = {
"mixed_precision": "fp16",
"log": "tensorboard",
}
PARAMS["seq2seq"] = {
"mixed_precision": "fp16",
"target_modules": "all-linear",
"log": "tensorboard",
}
PARAMS["tabular"] = {
"categorical_imputer": "most_frequent",
"numerical_imputer": "median",
"numeric_scaler": "robust",
}
PARAMS["token-classification"] = {
"mixed_precision": "fp16",
"log": "tensorboard",
}
PARAMS["text-regression"] = {
"mixed_precision": "fp16",
"log": "tensorboard",
}
PARAMS["image-regression"] = {
"mixed_precision": "fp16",
"log": "tensorboard",
}
PARAMS["vlm"] = {
"mixed_precision": "fp16",
"target_modules": "all-linear",
"log": "tensorboard",
"quantization": "int4",
"peft": True,
"epochs": 3,
}
PARAMS["extractive-qa"] = {
"mixed_precision": "fp16",
"log": "tensorboard",
"max_seq_length": 512,
"max_doc_stride": 128,
}
DEFAULT_COLUMN_MAPPING = {}
DEFAULT_COLUMN_MAPPING["llm:sft"] = {"text_column": "text"}
DEFAULT_COLUMN_MAPPING["llm:generic"] = {"text_column": "text"}
DEFAULT_COLUMN_MAPPING["llm:default"] = {"text_column": "text"}
DEFAULT_COLUMN_MAPPING["llm:dpo"] = {
"prompt_column": "prompt",
"text_column": "chosen",
"rejected_text_column": "rejected",
}
DEFAULT_COLUMN_MAPPING["llm:orpo"] = {
"prompt_column": "prompt",
"text_column": "chosen",
"rejected_text_column": "rejected",
}
DEFAULT_COLUMN_MAPPING["llm:reward"] = {"text_column": "chosen", "rejected_text_column": "rejected"}
DEFAULT_COLUMN_MAPPING["vlm:captioning"] = {"image_column": "image", "text_column": "caption"}
DEFAULT_COLUMN_MAPPING["vlm:vqa"] = {
"image_column": "image",
"prompt_text_column": "question",
"text_column": "answer",
}
DEFAULT_COLUMN_MAPPING["st:pair"] = {"sentence1": "anchor", "sentence2": "positive"}
DEFAULT_COLUMN_MAPPING["st:pair_class"] = {
"sentence1_column": "premise",
"sentence2_column": "hypothesis",
"target_column": "label",
}
DEFAULT_COLUMN_MAPPING["st:pair_score"] = {
"sentence1_column": "sentence1",
"sentence2_column": "sentence2",
"target_column": "score",
}
DEFAULT_COLUMN_MAPPING["st:triplet"] = {
"sentence1_column": "anchor",
"sentence2_column": "positive",
"sentence3_column": "negative",
}
DEFAULT_COLUMN_MAPPING["st:qa"] = {"sentence1_column": "query", "sentence2_column": "answer"}
DEFAULT_COLUMN_MAPPING["text-classification"] = {"text_column": "text", "target_column": "target"}
DEFAULT_COLUMN_MAPPING["seq2seq"] = {"text_column": "text", "target_column": "target"}
DEFAULT_COLUMN_MAPPING["text-regression"] = {"text_column": "text", "target_column": "target"}
DEFAULT_COLUMN_MAPPING["token-classification"] = {"text_column": "tokens", "target_column": "tags"}
DEFAULT_COLUMN_MAPPING["image-classification"] = {"image_column": "image", "target_column": "label"}
DEFAULT_COLUMN_MAPPING["image-regression"] = {"image_column": "image", "target_column": "target"}
DEFAULT_COLUMN_MAPPING["image-object-detection"] = {"image_column": "image", "objects_column": "objects"}
DEFAULT_COLUMN_MAPPING["tabular:classification"] = {"id_column": "id", "target__columns": ["target"]}
DEFAULT_COLUMN_MAPPING["tabular:regression"] = {"id_column": "id", "target_columns": ["target"]}
DEFAULT_COLUMN_MAPPING["extractive-qa"] = {
"text_column": "context",
"question_column": "question",
"answer_column": "answers",
}
VALID_TASKS = [k for k in DEFAULT_COLUMN_MAPPING.keys()]
@dataclass
class Client:
"""
A client to interact with the AutoTrain API.
Attributes:
host (Optional[str]): The host URL for the AutoTrain API.
token (Optional[str]): The authentication token for the API.
username (Optional[str]): The username for the API.
Methods:
__post_init__():
Initializes the client with default values if not provided and sets up headers.
__str__():
Returns a string representation of the client with masked token.
__repr__():
Returns a string representation of the client with masked token.
create(project_name: str, task: str, base_model: str, hardware: str, dataset: str, train_split: str, column_mapping: Optional[dict] = None, params: Optional[dict] = None, valid_split: Optional[str] = None):
Creates a new project on the AutoTrain platform.
get_logs(job_id: str):
Retrieves logs for a given job ID.
stop_training(job_id: str):
Stops the training for a given job ID.
"""
host: Optional[str] = None
token: Optional[str] = None
username: Optional[str] = None
def __post_init__(self):
if self.host is None:
self.host = AUTOTRAIN_API
if self.token is None:
self.token = os.environ.get("HF_TOKEN")
if self.username is None:
self.username = os.environ.get("HF_USERNAME")
if self.token is None or self.username is None:
raise ValueError("Please provide a valid username and token")
self.headers = {"Authorization": f"Bearer {self.token}", "Content-Type": "application/json"}
def __str__(self):
return f"Client(host={self.host}, token=****, username={self.username})"
def __repr__(self):
return self.__str__()
def create(
self,
project_name: str,
task: str,
base_model: str,
backend: str,
dataset: str,
train_split: str,
column_mapping: Optional[dict] = None,
params: Optional[dict] = None,
valid_split: Optional[str] = None,
):
if task not in VALID_TASKS:
raise ValueError(f"Invalid task. Valid tasks are: {VALID_TASKS}")
if backend not in BACKENDS:
raise ValueError(f"Invalid backend. Valid backends are: {list(BACKENDS.keys())}")
url = f"{self.host}/api/create_project"
if task == "llm:defaut":
task = "llm:generic"
if params is None:
params = {}
if task.startswith("llm"):
params = {k: v for k, v in PARAMS["llm"].items() if k not in params}
elif task.startswith("st"):
params = {k: v for k, v in PARAMS["st"].items() if k not in params}
else:
params = {k: v for k, v in PARAMS[task].items() if k not in params}
if column_mapping is None:
column_mapping = DEFAULT_COLUMN_MAPPING[task]
# check if column_mapping is valid for the task
default_col_map = DEFAULT_COLUMN_MAPPING[task]
missing_cols = []
for k, _ in default_col_map.items():
if k not in column_mapping.keys():
missing_cols.append(k)
if missing_cols:
raise ValueError(f"Missing columns in column_mapping: {missing_cols}")
data = {
"project_name": project_name,
"task": task,
"base_model": base_model,
"hardware": backend,
"params": params,
"username": self.username,
"column_mapping": column_mapping,
"hub_dataset": dataset,
"train_split": train_split,
"valid_split": valid_split,
}
response = requests.post(url, headers=self.headers, json=data)
if response.status_code == 200:
resp = response.json()
logger.info(
f"Project created successfully. Job ID: {resp['job_id']}. View logs at: https://hf.co/spaces/{resp['job_id']}"
)
return resp
else:
logger.error(f"Error creating project: {response.json()}")
return response.json()
def get_logs(self, job_id: str):
url = f"{self.host}/api/logs"
data = {"jid": job_id}
response = requests.post(url, headers=self.headers, json=data)
return response.json()
def stop_training(self, job_id: str):
url = f"{self.host}/api/stop_training/{job_id}"
data = {"jid": job_id}
response = requests.post(url, headers=self.headers, json=data)
return response.json()
|