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