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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# bert-class.py
|
| 2 |
+
# Model training script for BERT-based sequence classification
|
| 3 |
+
# This script uses the Hugging Face Transformers library to train a BERT model
|
| 4 |
+
# for binary classification tasks, such as detecting potential violations in housing data.
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import numpy as np
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
from typing import Dict, Any, Optional
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
from datasets import load_dataset
|
| 15 |
+
from transformers import (
|
| 16 |
+
AutoTokenizer,
|
| 17 |
+
AutoModelForSequenceClassification,
|
| 18 |
+
DataCollatorWithPadding,
|
| 19 |
+
TrainingArguments,
|
| 20 |
+
Trainer,
|
| 21 |
+
)
|
| 22 |
+
import evaluate
|
| 23 |
+
from sklearn.utils.class_weight import compute_class_weight
|
| 24 |
+
|
| 25 |
+
# =============================
|
| 26 |
+
# Settings
|
| 27 |
+
# =============================
|
| 28 |
+
MODEL_NAME = os.getenv("MODEL_NAME", "google/bert_uncased_L-2_H-128_A-2")
|
| 29 |
+
HUB_REPO = os.getenv("HUB_REPO", "tlogandesigns/fairhousing-bert-tiny")
|
| 30 |
+
MAX_LEN = int(os.getenv("MAX_LEN", "256"))
|
| 31 |
+
|
| 32 |
+
TRAIN_PATH = os.getenv("TRAIN_PATH", "train.csv")
|
| 33 |
+
VAL_PATH = os.getenv("VAL_PATH", "val.csv")
|
| 34 |
+
|
| 35 |
+
# Use binary labels 0/1
|
| 36 |
+
id2label = {0: "Compliant", 1: "Potential Violation"}
|
| 37 |
+
label2id = {v: k for k, v in id2label.items()}
|
| 38 |
+
|
| 39 |
+
# Metrics
|
| 40 |
+
accuracy = evaluate.load("accuracy")
|
| 41 |
+
precision = evaluate.load("precision")
|
| 42 |
+
recall = evaluate.load("recall")
|
| 43 |
+
f1 = evaluate.load("f1")
|
| 44 |
+
|
| 45 |
+
# =============================
|
| 46 |
+
# Data
|
| 47 |
+
# =============================
|
| 48 |
+
|
| 49 |
+
data_files = {"train": TRAIN_PATH, "validation": VAL_PATH}
|
| 50 |
+
raw = load_dataset("csv", data_files=data_files)
|
| 51 |
+
|
| 52 |
+
# ensure labels are ints
|
| 53 |
+
|
| 54 |
+
def cast_label(example):
|
| 55 |
+
example["label"] = int(example["label"])
|
| 56 |
+
return example
|
| 57 |
+
|
| 58 |
+
raw = raw.map(cast_label)
|
| 59 |
+
|
| 60 |
+
# Tokenizer
|
| 61 |
+
try:
|
| 62 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, use_fast=True)
|
| 63 |
+
except Exception:
|
| 64 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def tokenize(batch):
|
| 68 |
+
return tokenizer(
|
| 69 |
+
batch["text"],
|
| 70 |
+
truncation=True,
|
| 71 |
+
padding=False,
|
| 72 |
+
max_length=MAX_LEN,
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
# tokenize and keep only model inputs + labels
|
| 76 |
+
tok = raw.map(tokenize, batched=True)
|
| 77 |
+
|
| 78 |
+
# Rename for HF Trainer
|
| 79 |
+
if "label" in tok["train"].column_names:
|
| 80 |
+
tok = tok.rename_column("label", "labels")
|
| 81 |
+
|
| 82 |
+
# Remove non-input columns safely (token_type_ids may not exist for some models)
|
| 83 |
+
keep = {"input_ids", "attention_mask", "token_type_ids", "labels"}
|
| 84 |
+
cols = tok["train"].column_names
|
| 85 |
+
remove_cols = [c for c in cols if c not in keep]
|
| 86 |
+
if remove_cols:
|
| 87 |
+
tok = tok.remove_columns(remove_cols)
|
| 88 |
+
|
| 89 |
+
# Set PyTorch format
|
| 90 |
+
tok.set_format(type="torch")
|
| 91 |
+
|
| 92 |
+
train_ds = tok["train"]
|
| 93 |
+
val_ds = tok["validation"]
|
| 94 |
+
|
| 95 |
+
# Collator
|
| 96 |
+
data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
|
| 97 |
+
|
| 98 |
+
# =============================
|
| 99 |
+
# Class Weights (robust)
|
| 100 |
+
# =============================
|
| 101 |
+
|
| 102 |
+
# Derive labels from dataset (ensure 0/1 only)
|
| 103 |
+
y_train = train_ds["labels"].detach().cpu().numpy() if hasattr(train_ds["labels"], "detach") else np.array(train_ds["labels"]) # type: ignore
|
| 104 |
+
unique = np.unique(y_train)
|
| 105 |
+
|
| 106 |
+
# Guardrail: map any {0,1,2} style into binary if needed
|
| 107 |
+
if set(unique) - {0, 1}:
|
| 108 |
+
# Conservative mapping: {1,2}->1, 0->0
|
| 109 |
+
def to_bin(v: int) -> int:
|
| 110 |
+
return 0 if int(v) == 0 else 1
|
| 111 |
+
raw = raw.map(lambda ex: {"label": to_bin(int(ex["label"]))})
|
| 112 |
+
tok = raw.map(tokenize, batched=True)
|
| 113 |
+
if "label" in tok["train"].column_names:
|
| 114 |
+
tok = tok.rename_column("label", "labels")
|
| 115 |
+
cols = tok["train"].column_names
|
| 116 |
+
remove_cols = [c for c in cols if c not in keep]
|
| 117 |
+
if remove_cols:
|
| 118 |
+
tok = tok.remove_columns(remove_cols)
|
| 119 |
+
tok.set_format(type="torch")
|
| 120 |
+
train_ds = tok["train"]
|
| 121 |
+
val_ds = tok["validation"]
|
| 122 |
+
y_train = train_ds["labels"].detach().cpu().numpy() if hasattr(train_ds["labels"], "detach") else np.array(train_ds["labels"]) # type: ignore
|
| 123 |
+
unique = np.unique(y_train)
|
| 124 |
+
|
| 125 |
+
assert set(unique) <= {0, 1}, f"Found unexpected labels: {unique} — ensure CSVs are binary 0/1."
|
| 126 |
+
|
| 127 |
+
# Environment override: CLASS_WEIGHTS="1.0,3.0"
|
| 128 |
+
CW_ENV = os.getenv("CLASS_WEIGHTS", "")
|
| 129 |
+
if CW_ENV:
|
| 130 |
+
cw = np.array([float(x) for x in CW_ENV.split(",")], dtype=np.float32)
|
| 131 |
+
assert cw.shape[0] == 2, "CLASS_WEIGHTS must have 2 values for binary classification."
|
| 132 |
+
else:
|
| 133 |
+
cw = compute_class_weight(class_weight="balanced", classes=np.array([0, 1]), y=y_train).astype(np.float32)
|
| 134 |
+
class_weights_tensor = torch.tensor(cw, dtype=torch.float32)
|
| 135 |
+
|
| 136 |
+
# =============================
|
| 137 |
+
# Model
|
| 138 |
+
# =============================
|
| 139 |
+
|
| 140 |
+
torch.set_num_threads(max(1, (os.cpu_count() or 2) // 2))
|
| 141 |
+
model = AutoModelForSequenceClassification.from_pretrained(
|
| 142 |
+
MODEL_NAME,
|
| 143 |
+
num_labels=2,
|
| 144 |
+
id2label=id2label,
|
| 145 |
+
label2id={k: v for v, k in id2label.items()},
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
# =============================
|
| 149 |
+
# Weighted Trainer
|
| 150 |
+
# =============================
|
| 151 |
+
|
| 152 |
+
class WeightedTrainer(Trainer):
|
| 153 |
+
def __init__(self, *args, class_weights: Optional[torch.Tensor] = None, **kwargs):
|
| 154 |
+
super().__init__(*args, **kwargs)
|
| 155 |
+
self.class_weights = class_weights
|
| 156 |
+
self._ce_loss: Optional[nn.Module] = None
|
| 157 |
+
|
| 158 |
+
def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
|
| 159 |
+
labels = inputs.pop("labels", None)
|
| 160 |
+
outputs = model(**inputs)
|
| 161 |
+
logits = outputs.get("logits")
|
| 162 |
+
if labels is None:
|
| 163 |
+
loss = outputs["loss"] if "loss" in outputs else None
|
| 164 |
+
else:
|
| 165 |
+
if self._ce_loss is None:
|
| 166 |
+
if self.class_weights is not None:
|
| 167 |
+
self._ce_loss = nn.CrossEntropyLoss(weight=self.class_weights.to(model.device))
|
| 168 |
+
else:
|
| 169 |
+
self._ce_loss = nn.CrossEntropyLoss()
|
| 170 |
+
if labels.dtype != torch.long:
|
| 171 |
+
labels = labels.to(torch.long)
|
| 172 |
+
loss = self._ce_loss(logits, labels)
|
| 173 |
+
return (loss, outputs) if return_outputs else loss
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def compute_metrics(eval_pred):
|
| 177 |
+
logits, labels = eval_pred
|
| 178 |
+
preds = np.argmax(logits, axis=1)
|
| 179 |
+
return {
|
| 180 |
+
"accuracy": accuracy.compute(predictions=preds, references=labels)["accuracy"],
|
| 181 |
+
"precision": precision.compute(predictions=preds, references=labels, average="binary")["precision"],
|
| 182 |
+
"recall": recall.compute(predictions=preds, references=labels, average="binary")["recall"],
|
| 183 |
+
"f1": f1.compute(predictions=preds, references=labels, average="binary")["f1"],
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
# =============================
|
| 187 |
+
# Training Args
|
| 188 |
+
# =============================
|
| 189 |
+
|
| 190 |
+
args = TrainingArguments(
|
| 191 |
+
output_dir="runs",
|
| 192 |
+
eval_strategy="epoch", # <-- correct key
|
| 193 |
+
save_strategy="epoch",
|
| 194 |
+
logging_strategy="steps",
|
| 195 |
+
logging_steps=50,
|
| 196 |
+
|
| 197 |
+
per_device_train_batch_size=16,
|
| 198 |
+
per_device_eval_batch_size=32,
|
| 199 |
+
gradient_accumulation_steps=2,
|
| 200 |
+
num_train_epochs=5,
|
| 201 |
+
learning_rate=3e-5,
|
| 202 |
+
warmup_ratio=0.1,
|
| 203 |
+
weight_decay=0.01,
|
| 204 |
+
|
| 205 |
+
load_best_model_at_end=True,
|
| 206 |
+
metric_for_best_model="f1",
|
| 207 |
+
greater_is_better=True,
|
| 208 |
+
|
| 209 |
+
report_to=[], # disable W&B et al.
|
| 210 |
+
seed=42,
|
| 211 |
+
dataloader_pin_memory=False,
|
| 212 |
+
|
| 213 |
+
push_to_hub=bool(HUB_REPO),
|
| 214 |
+
hub_model_id=HUB_REPO,
|
| 215 |
+
hub_private_repo=False,
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
trainer = WeightedTrainer(
|
| 219 |
+
model=model,
|
| 220 |
+
args=args,
|
| 221 |
+
train_dataset=train_ds,
|
| 222 |
+
eval_dataset=val_ds,
|
| 223 |
+
tokenizer=tokenizer,
|
| 224 |
+
data_collator=data_collator,
|
| 225 |
+
class_weights=class_weights_tensor,
|
| 226 |
+
compute_metrics=compute_metrics,
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
trainer.train()
|
| 230 |
+
|
| 231 |
+
metrics = trainer.evaluate()
|
| 232 |
+
print("Eval:", metrics)
|
| 233 |
+
|
| 234 |
+
trainer.save_model("model")
|
| 235 |
+
try:
|
| 236 |
+
tokenizer.save_pretrained("model")
|
| 237 |
+
except Exception:
|
| 238 |
+
pass
|
| 239 |
+
|
| 240 |
+
if HUB_REPO:
|
| 241 |
+
try:
|
| 242 |
+
trainer.push_to_hub()
|
| 243 |
+
tokenizer.push_to_hub(HUB_REPO)
|
| 244 |
+
print(f"Pushed model to {HUB_REPO}")
|
| 245 |
+
except Exception as e:
|
| 246 |
+
print(f"Skipping hub push: {e}")
|
| 247 |
+
else:
|
| 248 |
+
print("No hub repo specified, model not pushed.")
|