basalt

examples/ai/fit_qwen_head.bas

' Train a linear classifier on fixed, centered Qwen feature vectors.
EXTERN FeatureWidth(0) FROM "./features.so"
EXTERN FeatureCount(0) FROM "./features.so"
EXTERN TrainCount(0) FROM "./features.so"
EXTERN FeatureAt(2) FROM "./features.so"
EXTERN LabelAt(1) FROM "./features.so"
LET width = FeatureWidth()
LET rows = FeatureCount()
LET train = TrainCount()
LET x = NEW Float[width * rows]
LET w = NEW Float[width]
LET labels = NEW Float[rows]
LET row = 0
WHILE row < rows
    labels[row] = FLOAT(LabelAt(row))
    LET j = 0
    WHILE j < width
        x[row * width + j] = FLOAT(FeatureAt(row, j)) / 4096.0
        j = j + 1
    WEND
    row = row + 1
WEND
LET bias = 0.0
LET epoch = 0
WHILE epoch < ARG
    row = 0
    WHILE row < train
        LET prediction = bias
        j = 0
        WHILE j < width
            prediction = prediction + w[j] * x[row * width + j]
            j = j + 1
        WEND
        LET update = 0.12 * (labels[row] - prediction)
        bias = bias + update
        j = 0
        WHILE j < width
            w[j] = w[j] + update * x[row * width + j]
            j = j + 1
        WEND
        row = row + 1
    WEND
    epoch = epoch + 1
WEND
LET loss = 0.0
LET correct = 0
row = train
WHILE row < rows
    prediction = bias
    j = 0
    WHILE j < width
        prediction = prediction + w[j] * x[row * width + j]
        j = j + 1
    WEND
    LET error = prediction - labels[row]
    loss = loss + error * error
    LET result = -1
    IF prediction > 0 THEN
        result = 1
    ENDIF
    PRINT result
    IF result = labels[row] THEN
        correct = correct + 1
    ENDIF
    row = row + 1
WEND
PRINT correct
PRINT loss / (rows - train)