Upload train.py
Browse files
train.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, pickle, numpy as np, pandas as pd, torch, torch.nn as nn
|
| 2 |
+
from datasets import load_dataset
|
| 3 |
+
from transformers import AutoModelForSeq2SeqLM, AutoConfig, TrainingArguments, Trainer, EarlyStoppingCallback, set_seed
|
| 4 |
+
from peft import LoraConfig, get_peft_model, TaskType
|
| 5 |
+
import trackio
|
| 6 |
+
from sklearn.preprocessing import StandardScaler, LabelEncoder
|
| 7 |
+
|
| 8 |
+
SEED=42; MODEL_NAME='amazon/chronos-bolt-small'; OUTPUT_DIR='/tmp/outputs'
|
| 9 |
+
HUB_MODEL_ID='superdkj/retail-world-model-v1'; DATASET_NAME='t4tiana/store-sales-time-series-forecasting'
|
| 10 |
+
CONTEXT_LENGTH=60; PREDICTION_LENGTH=14; NUM_VARIATES=5; EMBED_DIM=64
|
| 11 |
+
set_seed(SEED)
|
| 12 |
+
trackio.init(project='retail-world-model', run_name='retail-world-model-v1')
|
| 13 |
+
|
| 14 |
+
class RetailWorldModel(nn.Module):
|
| 15 |
+
def __init__(self, base_model_name, context_len, pred_len, num_variates, embed_dim):
|
| 16 |
+
super().__init__()
|
| 17 |
+
self.config = AutoConfig.from_pretrained(base_model_name)
|
| 18 |
+
self.encoder = AutoModelForSeq2SeqLM.from_pretrained(base_model_name)
|
| 19 |
+
self.context_len=context_len; self.pred_len=pred_len
|
| 20 |
+
self.num_variates=num_variates; self.embed_dim=embed_dim
|
| 21 |
+
self.input_proj = nn.Linear(num_variates, self.config.d_model)
|
| 22 |
+
self.latent_dynamics = nn.LSTM(self.config.d_model, self.config.d_model, 2, batch_first=True, dropout=0.1)
|
| 23 |
+
self.mean_head = nn.Sequential(nn.Linear(self.config.d_model, embed_dim), nn.GELU(), nn.Linear(embed_dim, 1))
|
| 24 |
+
self.var_head = nn.Sequential(nn.Linear(self.config.d_model, embed_dim), nn.GELU(), nn.Linear(embed_dim, 1), nn.Softplus())
|
| 25 |
+
def forward(self, context, target=None, return_loss=True):
|
| 26 |
+
x = self.input_proj(context)
|
| 27 |
+
enc_out = self.encoder.encoder(inputs_embeds=x, return_dict=True).last_hidden_state
|
| 28 |
+
h0 = enc_out[:, -1:, :].transpose(0, 1).repeat(2, 1, 1)
|
| 29 |
+
c0 = torch.zeros_like(h0)
|
| 30 |
+
states=[]; curr = enc_out[:, -1:, :]
|
| 31 |
+
for _ in range(self.pred_len):
|
| 32 |
+
out, (h0, c0) = self.latent_dynamics(curr, (h0, c0))
|
| 33 |
+
states.append(out); curr=out
|
| 34 |
+
states = torch.cat(states, dim=1)
|
| 35 |
+
mean = self.mean_head(states).squeeze(-1)
|
| 36 |
+
var = self.var_head(states).squeeze(-1)
|
| 37 |
+
if return_loss and target is not None:
|
| 38 |
+
loss = torch.mean(0.5 * torch.log(var+1e-6) + 0.5 * (target-mean)**2 / (var+1e-6))
|
| 39 |
+
return {'loss': loss, 'mean': mean, 'var': var}
|
| 40 |
+
return {'mean': mean, 'var': var}
|
| 41 |
+
|
| 42 |
+
class RetailDataset(torch.utils.data.Dataset):
|
| 43 |
+
def __init__(self, df, context_len=60, pred_len=14, scaler=None, fit_scaler=False):
|
| 44 |
+
self.context_len=context_len; self.pred_len=pred_len
|
| 45 |
+
df = df.copy()
|
| 46 |
+
df['date'] = pd.to_datetime(df['date'])
|
| 47 |
+
df['day_of_week'] = df['date'].dt.dayofweek / 6.0
|
| 48 |
+
df['month'] = df['date'].dt.month / 12.0
|
| 49 |
+
self.family_enc = LabelEncoder()
|
| 50 |
+
df['family_enc'] = self.family_enc.fit_transform(df['family'])
|
| 51 |
+
df['family_enc'] = df['family_enc'] / len(self.family_enc.classes_)
|
| 52 |
+
self.groups=[]
|
| 53 |
+
for _, g in df.groupby(['store_nbr', 'family']):
|
| 54 |
+
g = g.sort_values('date').reset_index(drop=True)
|
| 55 |
+
if len(g) >= context_len + pred_len: self.groups.append(g)
|
| 56 |
+
if scaler is None:
|
| 57 |
+
all_sales = np.concatenate([g['sales'].values for g in self.groups])
|
| 58 |
+
self.scaler = StandardScaler()
|
| 59 |
+
self.scaler.fit(all_sales.reshape(-1, 1))
|
| 60 |
+
else: self.scaler = scaler
|
| 61 |
+
for i, g in enumerate(self.groups):
|
| 62 |
+
g = g.copy()
|
| 63 |
+
g['sales_scaled'] = self.scaler.transform(g['sales'].values.reshape(-1, 1)).flatten()
|
| 64 |
+
self.groups[i] = g
|
| 65 |
+
self.windows=[]
|
| 66 |
+
for g in self.groups:
|
| 67 |
+
for start in range(0, len(g) - context_len - pred_len + 1, 7):
|
| 68 |
+
end_ctx = start + context_len
|
| 69 |
+
end_pred = end_ctx + pred_len
|
| 70 |
+
ctx = g.iloc[start:end_ctx][['sales_scaled','onpromotion','day_of_week','month','family_enc']].values.astype(np.float32)
|
| 71 |
+
tgt = g.iloc[end_ctx:end_pred]['sales_scaled'].values.astype(np.float32)
|
| 72 |
+
self.windows.append((ctx, tgt))
|
| 73 |
+
def __len__(self): return len(self.windows)
|
| 74 |
+
def __getitem__(self, idx):
|
| 75 |
+
ctx, tgt = self.windows[idx]
|
| 76 |
+
return {'context': torch.tensor(ctx), 'target': torch.tensor(tgt)}
|
| 77 |
+
|
| 78 |
+
def collate_fn(batch):
|
| 79 |
+
return {'context': torch.stack([b['context'] for b in batch]), 'target': torch.stack([b['target'] for b in batch])}
|
| 80 |
+
|
| 81 |
+
class RetailTrainer(Trainer):
|
| 82 |
+
def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
|
| 83 |
+
out = model(inputs['context'], inputs['target'], return_loss=True)
|
| 84 |
+
loss = out['loss']
|
| 85 |
+
if return_outputs: return loss, out
|
| 86 |
+
return loss
|
| 87 |
+
def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys=None):
|
| 88 |
+
with torch.no_grad(): out = model(inputs['context'], inputs['target'], return_loss=True)
|
| 89 |
+
loss = out['loss']
|
| 90 |
+
if prediction_loss_only: return (loss, None, None)
|
| 91 |
+
return (loss, out['mean'], inputs['target'])
|
| 92 |
+
|
| 93 |
+
print('Loading dataset...')
|
| 94 |
+
ds = load_dataset(DATASET_NAME, split='train')
|
| 95 |
+
df = ds.to_pandas()
|
| 96 |
+
print(f'Rows: {len(df)}, Stores: {df[\"store_nbr\"].nunique()}, Families: {df[\"family\"].nunique()}')
|
| 97 |
+
df['date'] = pd.to_datetime(df['date'])
|
| 98 |
+
split_date = df['date'].max() - pd.Timedelta(days=90)
|
| 99 |
+
train_df = df[df['date'] <= split_date]
|
| 100 |
+
val_df = df[df['date'] > split_date]
|
| 101 |
+
print(f'Train: {len(train_df)}, Val: {len(val_df)}')
|
| 102 |
+
|
| 103 |
+
print('Building datasets...')
|
| 104 |
+
train_ds = RetailDataset(train_df, CONTEXT_LENGTH, PREDICTION_LENGTH, fit_scaler=True)
|
| 105 |
+
val_ds = RetailDataset(val_df, CONTEXT_LENGTH, PREDICTION_LENGTH, scaler=train_ds.scaler, fit_scaler=False)
|
| 106 |
+
print(f'Train windows: {len(train_ds)}, Val windows: {len(val_ds)}')
|
| 107 |
+
|
| 108 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 109 |
+
with open(f'{OUTPUT_DIR}/scaler.pkl', 'wb') as f: pickle.dump(train_ds.scaler, f)
|
| 110 |
+
|
| 111 |
+
print('Initializing model...')
|
| 112 |
+
model = RetailWorldModel(MODEL_NAME, CONTEXT_LENGTH, PREDICTION_LENGTH, NUM_VARIATES, EMBED_DIM)
|
| 113 |
+
lora_cfg = LoraConfig(r=16, lora_alpha=32, target_modules=['q','v','k','o'], lora_dropout=0.05, bias='none', task_type=TaskType.SEQ_2_SEQ_LM)
|
| 114 |
+
model.encoder = get_peft_model(model.encoder, lora_cfg)
|
| 115 |
+
model.encoder.print_trainable_parameters()
|
| 116 |
+
|
| 117 |
+
args = TrainingArguments(
|
| 118 |
+
output_dir=OUTPUT_DIR, num_train_epochs=10, per_device_train_batch_size=32,
|
| 119 |
+
per_device_eval_batch_size=64, learning_rate=1e-4, weight_decay=0.01,
|
| 120 |
+
warmup_ratio=0.1, lr_scheduler_type='cosine', evaluation_strategy='epoch',
|
| 121 |
+
save_strategy='epoch', logging_strategy='steps', logging_steps=50,
|
| 122 |
+
logging_first_step=True, disable_tqdm=True, load_best_model_at_end=True,
|
| 123 |
+
metric_for_best_model='eval_loss', greater_is_better=False,
|
| 124 |
+
push_to_hub=True, hub_model_id=HUB_MODEL_ID, hub_strategy='every_save',
|
| 125 |
+
save_total_limit=2, report_to='trackio', run_name='retail-world-model-v1',
|
| 126 |
+
seed=SEED, dataloader_num_workers=4, gradient_accumulation_steps=2, fp16=True,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
trainer = RetailTrainer(
|
| 130 |
+
model=model, args=args, train_dataset=train_ds, eval_dataset=val_ds,
|
| 131 |
+
data_collator=collate_fn, callbacks=[EarlyStoppingCallback(early_stopping_patience=3)],
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
print('Training...')
|
| 135 |
+
trainer.train()
|
| 136 |
+
trainer.save_model(f'{OUTPUT_DIR}/final')
|
| 137 |
+
eval_results = trainer.evaluate()
|
| 138 |
+
print(f'Final eval_loss: {eval_results[\"eval_loss\"]:.4f}')
|
| 139 |
+
trackio.alert(title='Training Complete', text=f'Final eval_loss={eval_results[\"eval_loss\"]:.4f}', level='INFO')
|
| 140 |
+
trainer.push_to_hub()
|
| 141 |
+
print('Done!')
|