# xiao_transformer_speech.ino

- Project: [S-17](https://flashesp.com/explore/gJ93dA9NU5ZQ1xs5TMhxA.md) by 9643723
- Board: XIAO_ESP32S3
- Language: Arduino (C++)
- Web page: https://flashesp.com/explore/gJ93dA9NU5ZQ1xs5TMhxA/files/ahqW2whl2QjUfd6K0R5yL

```cpp
#include <WiFi.h>
#include <HTTPClient.h>
#include <WebServer.h>
#include <FS.h>
#include <LittleFS.h>
#include <math.h>
#include "brain_data.h"

// ==========================================
// 1. WIFI & HARDWARE PINS (Standard XIAO ESP32S3)
// ==========================================
const char* WIFI_SSID = "";
const char* WIFI_PASSWORD = "";

#define BUZZER_GPIO 3   // Pin D2 on XIAO ESP32S3 (GPIO 3)
#define TOUCH_PIN   D0  // Pin D0 (GPIO 1)
#define MIC_PIN     D1  // Pin D1 (GPIO 2)
#define LED_PIN     LED_BUILTIN // GPIO 21

// ==========================================
// 2. DATA STRUCTURES
// ==========================================
struct QTensor {
  float scale;
  uint32_t size;
  const int8_t* data;
};

struct LayerWeights {
  QTensor ln1_g, ln1_b;
  QTensor wq, wk, wv, wo;
  QTensor ln2_g, ln2_b;
  QTensor w1, b1, w2, b2;
};

struct HumanSkill {
  String name;
  String steps;
};

// ==========================================
// 3. SAM (SOFTWARE AUTOMATIC MOUTH) FORMANT ENGINE
// ==========================================
bool voiceEnabled = true;
int samPitch = 64;   // Classic SAM pitch (lower = deeper, default 64 ~ 115Hz)
int samSpeed = 72;   // Classic SAM speed (lower = faster, default 72)

struct SAMPhoneme {
  const char* code;
  uint16_t f1;
  uint16_t f2;
  uint16_t f3;
  uint8_t dur;      // Base frames (each frame ~10ms)
  uint8_t voiced;   // 1 = glottal buzz + formants, 0 = noise/fricative, 2 = silent stop
};

// Authentic SAM vowel & consonant formant table (F1, F2, F3 in Hz)
const SAMPhoneme SAM_TABLE[] = {
  {"IY",  270, 2290, 3010, 7, 1}, // feet
  {"IH",  390, 1990, 2550, 6, 1}, // pin
  {"EH",  530, 1840, 2480, 7, 1}, // pet
  {"AE",  660, 1720, 2410, 8, 1}, // cat
  {"AA",  730, 1090, 2440, 8, 1}, // father
  {"AO",  570,  840, 2410, 8, 1}, // dog
  {"UH",  440, 1020, 2240, 6, 1}, // book
  {"UW",  300,  870, 2240, 8, 1}, // food
  {"AH",  640, 1190, 2390, 6, 1}, // but
  {"ER",  490, 1350, 1690, 8, 1}, // bird
  {"AY",  700, 1250, 2500, 9, 1}, // my
  {"EY",  480, 2050, 2600, 9, 1}, // say
  {"OW",  450,  900, 2350, 9, 1}, // go
  {"AW",  700, 1150, 2400, 9, 1}, // how
  {"OY",  520, 1000, 2400, 9, 1}, // boy
  {"L*",  360, 1050, 2600, 5, 1},
  {"R*",  420, 1300, 1600, 5, 1},
  {"W*",  290,  750, 2200, 5, 1},
  {"Y*",  280, 2150, 2900, 5, 1},
  {"M*",  280,  900, 2200, 6, 1},
  {"N*",  280, 1700, 2600, 6, 1},
  {"Z*",  300, 1600, 2600, 6, 1},
  {"V*",  300, 1400, 2400, 5, 1},
  {"B*",  200,  900, 2100, 4, 1},
  {"D*",  250, 1700, 2600, 4, 1},
  {"G*",  250, 1300, 2300, 4, 1},
  {"S*", 1800, 3400, 4200, 7, 0},
  {"SH", 1500, 2600, 3500, 7, 0},
  {"F*", 1400, 2400, 3400, 6, 0},
  {"TH", 1300, 2200, 3200, 6, 0},
  {"CH", 1600, 2700, 3600, 6, 0},
  {"HH", 1100, 1900, 2800, 5, 0},
  {"P*",    0,    0,    0, 4, 2},
  {"T*",    0,    0,    0, 4, 2},
  {"K*",    0,    0,    0, 4, 2},
  {"  ",    0,    0,    0, 5, 2}
};
const int SAM_TABLE_LEN = sizeof(SAM_TABLE) / sizeof(SAM_TABLE[0]);

const SAMPhoneme* findPhoneme(const char* code) {
  for (int i = 0; i < SAM_TABLE_LEN; i++) {
    if (SAM_TABLE[i].code[0] == code[0] && SAM_TABLE[i].code[1] == code[1]) {
      return &SAM_TABLE[i];
    }
  }
  return &SAM_TABLE[SAM_TABLE_LEN - 1];
}

// Convert English text to SAM phoneme string
String englishToSAM(String text) {
  text.toUpperCase();
  String out = "";
  int n = text.length();
  for (int i = 0; i < n; i++) {
    char c = text[i];
    char nx = (i + 1 < n) ? text[i + 1] : ' ';
    char nx2 = (i + 2 < n) ? text[i + 2] : ' ';

    if (c == ' ' || c == ',' || c == '.' || c == '!' || c == '?') {
      out += "  ";
      continue;
    }
    if (c < 'A' || c > 'Z') continue;

    // Digraphs & common English rules
    if (c == 'T' && nx == 'H') { out += "TH"; i++; continue; }
    if (c == 'S' && nx == 'H') { out += "SH"; i++; continue; }
    if (c == 'C' && nx == 'H') { out += "CH"; i++; continue; }
    if (c == 'P' && nx == 'H') { out += "F*"; i++; continue; }
    if (c == 'E' && nx == 'E') { out += "IY"; i++; continue; }
    if (c == 'E' && nx == 'A') { out += "IY"; i++; continue; }
    if (c == 'O' && nx == 'O') { out += "UW"; i++; continue; }
    if (c == 'O' && nx == 'U') { out += "AW"; i++; continue; }
    if (c == 'O' && nx == 'W') { out += "OW"; i++; continue; }
    if (c == 'A' && nx == 'I') { out += "EY"; i++; continue; }
    if (c == 'A' && nx == 'Y') { out += "EY"; i++; continue; }
    if (c == 'O' && nx == 'Y') { out += "OY"; i++; continue; }
    if (c == 'O' && nx == 'I') { out += "OY"; i++; continue; }
    if (c == 'E' && nx == 'R') { out += "ER"; i++; continue; }
    if (c == 'I' && nx == 'R') { out += "ER"; i++; continue; }
    if (c == 'U' && nx == 'R') { out += "ER"; i++; continue; }
    if (c == 'A' && nx == 'R') { out += "AA"; i++; continue; }
    if (c == 'O' && nx == 'R') { out += "AO"; i++; continue; }
    if (c == 'M' && nx == 'Y' && nx2 == ' ') { out += "M*AY"; i++; continue; }
    if (c == 'H' && nx == 'I' && nx2 == ' ') { out += "HHAY"; i++; continue; }

    // Silent trailing E
    if (c == 'E' && (nx == ' ' || nx == '.' || nx == '!' || nx == '?') && i > 2) {
      continue;
    }

    switch (c) {
      case 'A': out += (nx2 == 'E') ? "EY" : "AE"; break;
      case 'E': out += "EH"; break;
      case 'I': out += (nx2 == 'E') ? "AY" : "IH"; break;
      case 'O': out += (nx2 == 'E') ? "OW" : "AA"; break;
      case 'U': out += "AH"; break;
      case 'Y': out += (i == 0) ? "Y*" : "IY"; break;
      case 'B': out += "B*"; break;
      case 'C': out += (nx == 'E' || nx == 'I') ? "S*" : "K*"; break;
      case 'D': out += "D*"; break;
      case 'F': out += "F*"; break;
      case 'G': out += "G*"; break;
      case 'H': out += "HH"; break;
      case 'J': out += "CH"; break;
      case 'K': out += "K*"; break;
      case 'L': out += "L*"; break;
      case 'M': out += "M*"; break;
      case 'N': out += "N*"; break;
      case 'P': out += "P*"; break;
      case 'Q': out += "K*W*"; break;
      case 'R': out += "R*"; break;
      case 'S': out += "S*"; break;
      case 'T': out += "T*"; break;
      case 'V': out += "V*"; break;
      case 'W': out += "W*"; break;
      case 'X': out += "K*S*"; break;
      case 'Z': out += "Z*"; break;
    }
  }
  return out;
}

// 11.025kHz High-Speed PWM Formant Synthesizer (Authentic SAM Buzz + F1/F2/F3 Harmonics)
void speakSAM(String text) {
  if (!voiceEnabled) return;
  text.trim();
  if (text.length() == 0) return;
  if (text.length() > 75) text = text.substring(0, 75);

  bool isQuestion = text.endsWith("?");
  String phonemes = englishToSAM(text);
  int numPh = phonemes.length() / 2;
  if (numPh == 0) return;

  // 31.25kHz 8-bit PWM carrier on GPIO 3 so the buzzer acts as a true DAC speaker
  ledcAttach(BUZZER_GPIO, 31250, 8);

  const uint32_t SAMPLE_RATE = 11025; // Classic SAM 11kHz DAC rate
  const uint32_t SAMPLE_US = 1000000UL / SAMPLE_RATE;

  float baseF0 = 7500.0f / (float)samPitch; // samPitch 64 -> ~117 Hz robotic buzz
  uint32_t glottalPhase = 0;
  uint32_t f1Phase = 0, f2Phase = 0, f3Phase = 0;
  uint32_t lfsr = 0xACE1u;

  float curF1 = 500.0f, curF2 = 1500.0f, curF3 = 2500.0f;

  for (int p = 0; p < numPh; p++) {
    char code[3] = { phonemes[p * 2], phonemes[p * 2 + 1], '\0' };
    const SAMPhoneme* ph = findPhoneme(code);

    // Prosody contour: flat robotic SAM cadence with pitch rise on questions
    float progress = (float)p / (float)numPh;
    float f0 = baseF0;
    if (isQuestion && progress > 0.72f) {
      f0 *= (1.0f + (progress - 0.72f) * 1.1f);
    } else if (progress > 0.85f) {
      f0 *= (1.0f - (progress - 0.85f) * 0.5f);
    }

    int frames = (ph->dur * samSpeed) / 72;
    if (frames < 2) frames = 2;
    int totalSamples = frames * (SAMPLE_RATE / 100); // ~10ms per frame

    uint32_t glottalInc = (uint32_t)((f0 / SAMPLE_RATE) * 4294967296.0f);

    for (int s = 0; s < totalSamples; s++) {
      uint32_t t0 = micros();

      // Smooth formant coarticulation between adjacent phonemes
      curF1 += (ph->f1 - curF1) * 0.015f;
      curF2 += (ph->f2 - curF2) * 0.015f;
      curF3 += (ph->f3 - curF3) * 0.015f;

      uint8_t sampleOut = 128;

      if (ph->voiced == 1) {
        // Classic SAM glottal sawtooth pulse + F1/F2/F3 formant resonances
        glottalPhase += glottalInc;
        uint8_t gPos = glottalPhase >> 24; // 0..255 sawtooth ramp

        // Reset formant phases synchronously at each glottal pulse (SAM's signature buzz!)
        if (gPos < (glottalInc >> 24)) {
          f1Phase = 0;
          f2Phase = 0;
          f3Phase = 0;
        }

        f1Phase += (uint32_t)((curF1 / SAMPLE_RATE) * 4294967296.0f);
        f2Phase += (uint32_t)((curF2 / SAMPLE_RATE) * 4294967296.0f);
        f3Phase += (uint32_t)((curF3 / SAMPLE_RATE) * 4294967296.0f);

        // Square/triangle formant waves damped across the glottal period
        int env = 255 - gPos;
        int w1 = ((f1Phase >> 31) ? 1 : -1) * 64;
        int w2 = ((f2Phase >> 31) ? 1 : -1) * 42;
        int w3 = ((f3Phase >> 31) ? 1 : -1) * 20;

        int mixed = 128 + (((w1 + w2 + w3) * env) >> 8);
        if (mixed < 0) mixed = 0;
        if (mixed > 255) mixed = 255;
        sampleOut = (uint8_t)mixed;
      } else if (ph->voiced == 0) {
        // Unvoiced fricative (S, SH, F, TH, H): bandpass-filtered LFSR noise
        uint32_t bit = ((lfsr >> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5)) & 1u;
        lfsr = (lfsr >> 1) | (bit << 15);
        f2Phase += (uint32_t)((curF2 / SAMPLE_RATE) * 4294967296.0f);
        int noise = (lfsr & 1) ? 55 : -55;
        int carrier = ((f2Phase >> 31) ? 1 : -1);
        sampleOut = (uint8_t)(128 + noise * carrier);
      } else {
        sampleOut = 128;
      }

      ledcWrite(BUZZER_GPIO, sampleOut);

      while ((uint32_t)(micros() - t0) < SAMPLE_US) {
        // Exact 11,025 Hz sample pacing
      }
    }
    yield(); // Keep Wi-Fi & watchdog happy between phonemes
  }

  ledcWrite(BUZZER_GPIO, 0);
  ledcDetach(BUZZER_GPIO);
}

// ==========================================
// 4. TRANSFORMER WEIGHTS & SAFE BUFFERS
// ==========================================
uint32_t V = 0, D = 0, N_LAYERS = 0, N_HEADS = 0, D_FF = 0, TRAIN_SEQ_LEN = 0;
#define MAX_SEQ_LEN 48

String* vocab = nullptr;
QTensor wte, wpe, ln_f_g, ln_f_b, lm_head, lm_bias;
LayerWeights* layers = nullptr;

float* buf_x = nullptr;
float* buf_ln = nullptr;
float* buf_q = nullptr;
float* buf_k = nullptr;
float* buf_v = nullptr;
float* buf_ff = nullptr;
float* buf_logits = nullptr;

#define MAX_MEMORIES 50
String memories[MAX_MEMORIES];
int memCount = 0;

#define MAX_SKILLS 20
HumanSkill skills[MAX_SKILLS];
int skillCount = 0;

WebServer server(80);
bool wifiConnected = false;
unsigned long lastInteractionTime = 0;
unsigned long lastExploreTime = 0;
String pendingQuestion = "";

// ==========================================
// 5. BINARY PARSER & PERSISTENT STORAGE
// ==========================================
uint16_t readU16(size_t& off) {
  uint16_t v = pgm_read_byte(brain_q8_bin + off) | (pgm_read_byte(brain_q8_bin + off + 1) << 8);
  off += 2;
  return v;
}

uint32_t readU32(size_t& off) {
  uint32_t v = (uint32_t)pgm_read_byte(brain_q8_bin + off) |
               ((uint32_t)pgm_read_byte(brain_q8_bin + off + 1) << 8) |
               ((uint32_t)pgm_read_byte(brain_q8_bin + off + 2) << 16) |
               ((uint32_t)pgm_read_byte(brain_q8_bin + off + 3) << 24);
  off += 4;
  return v;
}

float readF32(size_t& off) {
  uint32_t u = readU32(off);
  float f;
  memcpy(&f, &u, sizeof(float));
  return f;
}

QTensor readTensor(size_t& off) {
  QTensor t;
  t.scale = readF32(off);
  t.size = readU32(off);
  t.data = (const int8_t*)(brain_q8_bin + off);
  off += t.size;
  return t;
}

void saveMemoriesToFlash() {
  File f = LittleFS.open("/memories.txt", "w");
  if (!f) return;
  for (int i = 0; i < memCount; i++) f.println(memories[i]);
  f.close();
}

void addMemory(const String& line, bool persist = true) {
  String clean = line;
  clean.trim();
  if (clean.length() == 0) return;
  if (memCount < MAX_MEMORIES) {
    memories[memCount++] = clean;
  } else {
    for (int i = 1; i < MAX_MEMORIES; i++) memories[i - 1] = memories[i];
    memories[MAX_MEMORIES - 1] = clean;
  }
  if (persist) saveMemoriesToFlash();
}

void saveSkillsToFlash() {
  File f = LittleFS.open("/skills.txt", "w");
  if (!f) return;
  for (int i = 0; i < skillCount; i++) {
    f.println(skills[i].name + "|" + skills[i].steps);
  }
  f.close();
}

void learnSkill(const String& rawName, const String& rawSteps, bool persist = true) {
  String n = rawName; n.trim(); n.toLowerCase();
  String s = rawSteps; s.trim();
  if (n.length() == 0 || s.length() == 0) return;

  for (int i = 0; i < skillCount; i++) {
    if (skills[i].name == n) {
      skills[i].steps = s;
      if (persist) saveSkillsToFlash();
      return;
    }
  }
  if (skillCount < MAX_SKILLS) {
    skills[skillCount].name = n;
    skills[skillCount].steps = s;
    skillCount++;
  } else {
    for (int i = 1; i < MAX_SKILLS; i++) skills[i - 1] = skills[i];
    skills[MAX_SKILLS - 1].name = n;
    skills[MAX_SKILLS - 1].steps = s;
  }
  if (persist) saveSkillsToFlash();
}

void initDefaultSkills() {
  learnSkill("greet a human", "1. Smile and make eye contact. 2. Say hello warmly. 3. Ask how their day is going.", false);
  learnSkill("make tea", "1. Boil fresh water. 2. Place a tea bag in a mug. 3. Pour hot water and steep for 3 minutes.", false);
  learnSkill("solve math", "1. Read the numbers carefully. 2. Identify addition, subtraction, multiplication, or division. 3. Compute and double check.", false);
  learnSkill("blink morse", "1. Convert each letter to dots and dashes. 2. Flash the LED short for dots and long for dashes.", false);
  saveSkillsToFlash();
}

void loadPersistentStorage() {
  if (!LittleFS.begin(true)) {
    Serial.println("[Warning] LittleFS mount failed; using RAM-only memory.");
    return;
  }
  if (LittleFS.exists("/memories.txt")) {
    File f = LittleFS.open("/memories.txt", "r");
    if (f) {
      memCount = 0;
      while (f.available()) {
        String line = f.readStringUntil('\n');
        line.trim();
        if (line.length() > 0) addMemory(line, false);
      }
      f.close();
    }
  } else {
    saveMemoriesToFlash();
  }

  if (LittleFS.exists("/skills.txt")) {
    File f = LittleFS.open("/skills.txt", "r");
    if (f) {
      skillCount = 0;
      while (f.available()) {
        String line = f.readStringUntil('\n');
        int sep = line.indexOf('|');
        if (sep > 0) {
          learnSkill(line.substring(0, sep), line.substring(sep + 1), false);
        }
      }
      f.close();
    }
  } else {
    initDefaultSkills();
  }
}

bool loadBrain() {
  size_t off = 0;
  if (brain_q8_len < 28) return false;
  if (pgm_read_byte(brain_q8_bin) != 'Q' || pgm_read_byte(brain_q8_bin + 1) != '8') return false;
  off = 4;

  V = readU32(off);
  D = readU32(off);
  N_LAYERS = readU32(off);
  N_HEADS = readU32(off);
  D_FF = readU32(off);
  TRAIN_SEQ_LEN = readU32(off);

  vocab = new String[V];
  for (uint32_t i = 0; i < V; i++) {
    uint16_t len = readU16(off);
    char* tmp = (char*)malloc(len + 1);
    for (uint16_t j = 0; j < len; j++) tmp[j] = (char)pgm_read_byte(brain_q8_bin + off + j);
    tmp[len] = '\0';
    vocab[i] = String(tmp);
    free(tmp);
    off += len;
  }

  wte = readTensor(off);
  wpe = readTensor(off);
  ln_f_g = readTensor(off);
  ln_f_b = readTensor(off);
  lm_head = readTensor(off);
  lm_bias = readTensor(off);

  layers = new LayerWeights[N_LAYERS];
  for (uint32_t l = 0; l < N_LAYERS; l++) {
    layers[l].ln1_g = readTensor(off);
    layers[l].ln1_b = readTensor(off);
    layers[l].wq = readTensor(off);
    layers[l].wk = readTensor(off);
    layers[l].wv = readTensor(off);
    layers[l].wo = readTensor(off);
    layers[l].ln2_g = readTensor(off);
    layers[l].ln2_b = readTensor(off);
    layers[l].w1 = readTensor(off);
    layers[l].b1 = readTensor(off);
    layers[l].w2 = readTensor(off);
    layers[l].b2 = readTensor(off);
  }

  uint32_t numMem = readU32(off);
  for (uint32_t i = 0; i < numMem; i++) {
    uint16_t len = readU16(off);
    char* tmp = (char*)malloc(len + 1);
    for (uint16_t j = 0; j < len; j++) tmp[j] = (char)pgm_read_byte(brain_q8_bin + off + j);
    tmp[len] = '\0';
    addMemory(String(tmp), false);
    free(tmp);
    off += len;
  }

  buf_x      = (float*)malloc(MAX_SEQ_LEN * D * sizeof(float));
  buf_ln     = (float*)malloc(MAX_SEQ_LEN * D * sizeof(float));
  buf_q      = (float*)malloc(MAX_SEQ_LEN * D * sizeof(float));
  buf_k      = (float*)malloc(MAX_SEQ_LEN * D * sizeof(float));
  buf_v      = (float*)malloc(MAX_SEQ_LEN * D * sizeof(float));
  buf_ff     = (float*)malloc(MAX_SEQ_LEN * D_FF * sizeof(float));
  buf_logits = (float*)malloc(V * sizeof(float));

  if (!buf_x || !buf_ln || !buf_q || !buf_k || !buf_v || !buf_ff || !buf_logits) {
    return false;
  }

  Serial.printf("[Brain Loaded] Vocab: %u | Dim: %u | Layers: %u | Free Heap: %u bytes\n",
                V, D, N_LAYERS, ESP.getFreeHeap());
  return true;
}

// ==========================================
// 6. INT8 TRANSFORMER FORWARD PASS
// ==========================================
int findToken(const String& tok) {
  for (uint32_t i = 0; i < V; i++) {
    if (vocab[i] == tok) return (int)i;
  }
  return 1;
}

int tokenize(const String& text, int* outIds, int maxTokens) {
  int count = 0;
  int n = text.length();
  int i = 0;
  while (i < n && count < maxTokens) {
    while (i < n && text[i] == ' ') i++;
    if (i >= n) break;
    if (text[i] == '<') {
      int endTag = text.indexOf('>', i);
      if (endTag > i) {
        outIds[count++] = findToken(text.substring(i, endTag + 1));
        i = endTag + 1;
        continue;
      }
    }
    char c = text[i];
    if (c == '.' || c == ',' || c == '!' || c == '?' || c == ';' || c == ':' || c == '\n') {
      outIds[count++] = findToken(String(c));
      i++;
      continue;
    }
    int start = i;
    while (i < n && text[i] != ' ' && text[i] != '<' &&
           text[i] != '.' && text[i] != ',' && text[i] != '!' && text[i] != '?' && text[i] != '\n') {
      i++;
    }
    outIds[count++] = findToken(text.substring(start, i));
  }
  return count;
}

void layerNorm(float* out, const float* in, const QTensor& g, const QTensor& b, int T) {
  for (int t = 0; t < T; t++) {
    const float* row = in + t * D;
    float* dst = out + t * D;
    float mean = 0.0f;
    for (uint32_t d = 0; d < D; d++) mean += row[d];
    mean /= D;
    float var = 0.0f;
    for (uint32_t d = 0; d < D; d++) {
      float diff = row[d] - mean;
      var += diff * diff;
    }
    float invStd = 1.0f / sqrtf(var / D + 1e-5f);
    for (uint32_t d = 0; d < D; d++) {
      float gv = (int8_t)pgm_read_byte(g.data + d) * g.scale;
      float bv = (int8_t)pgm_read_byte(b.data + d) * b.scale;
      dst[d] = ((row[d] - mean) * invStd) * gv + bv;
    }
  }
}

void matmulQ8(float* out, const float* in, const QTensor& w, int T, int inDim, int outDim) {
  for (int t = 0; t < T; t++) {
    const float* row = in + t * inDim;
    float* dst = out + t * outDim;
    for (int o = 0; o < outDim; o++) {
      float sum = 0.0f;
      for (int i = 0; i < inDim; i++) {
        int8_t qv = (int8_t)pgm_read_byte(w.data + (i * outDim + o));
        sum += row[i] * (qv * w.scale);
      }
      dst[o] = sum;
    }
  }
}

void forwardStep(const int* ids, int T) {
  uint32_t dHead = D / N_HEADS;
  float invSqrtD = 1.0f / sqrtf((float)dHead);

  for (int t = 0; t < T; t++) {
    int id = ids[t];
    int pos = (t < (int)TRAIN_SEQ_LEN) ? t : (int)TRAIN_SEQ_LEN - 1;
    for (uint32_t d = 0; d < D; d++) {
      float te = (int8_t)pgm_read_byte(wte.data + (id * D + d)) * wte.scale;
      float pe = (int8_t)pgm_read_byte(wpe.data + (pos * D + d)) * wpe.scale;
      buf_x[t * D + d] = te + pe;
    }
  }

  float scores[MAX_SEQ_LEN];

  for (uint32_t l = 0; l < N_LAYERS; l++) {
    layerNorm(buf_ln, buf_x, layers[l].ln1_g, layers[l].ln1_b, T);
    matmulQ8(buf_q, buf_ln, layers[l].wq, T, D, D);
    matmulQ8(buf_k, buf_ln, layers[l].wk, T, D, D);
    matmulQ8(buf_v, buf_ln, layers[l].wv, T, D, D);

    for (int t = 0; t < T; t++) {
      for (uint32_t h = 0; h < N_HEADS; h++) {
        uint32_t hOff = h * dHead;
        float maxScore = -1e9f;
        for (int s = 0; s <= t; s++) {
          float dot = 0.0f;
          for (uint32_t d = 0; d < dHead; d++) {
            dot += buf_q[t * D + hOff + d] * buf_k[s * D + hOff + d];
          }
          scores[s] = dot * invSqrtD;
          if (scores[s] > maxScore) maxScore = scores[s];
        }
        float sumExp = 0.0f;
        for (int s = 0; s <= t; s++) {
          scores[s] = expf(scores[s] - maxScore);
          sumExp += scores[s];
        }
        for (uint32_t d = 0; d < dHead; d++) {
          float weighted = 0.0f;
          for (int s = 0; s <= t; s++) {
            weighted += (scores[s] / sumExp) * buf_v[s * D + hOff + d];
          }
          buf_ln[t * D + hOff + d] = weighted;
        }
      }
    }

    matmulQ8(buf_q, buf_ln, layers[l].wo, T, D, D);
    for (uint32_t i = 0; i < (uint32_t)(T * D); i++) buf_x[i] += buf_q[i];

    layerNorm(buf_ln, buf_x, layers[l].ln2_g, layers[l].ln2_b, T);
    matmulQ8(buf_ff, buf_ln, layers[l].w1, T, D, D_FF);
    for (int t = 0; t < T; t++) {
      for (uint32_t f = 0; f < D_FF; f++) {
        float b1v = (int8_t)pgm_read_byte(layers[l].b1.data + f) * layers[l].b1.scale;
        float val = buf_ff[t * D_FF + f] + b1v;
        buf_ff[t * D_FF + f] = (val > 0.0f) ? val : 0.0f;
      }
    }
    matmulQ8(buf_q, buf_ff, layers[l].w2, T, D_FF, D);
    for (int t = 0; t < T; t++) {
      for (uint32_t d = 0; d < D; d++) {
        float b2v = (int8_t)pgm_read_byte(layers[l].b2.data + d) * layers[l].b2.scale;
        buf_x[t * D + d] += buf_q[t * D + d] + b2v;
      }
    }
    yield();
  }

  layerNorm(buf_ln, buf_x, ln_f_g, ln_f_b, T);
  const float* lastRow = buf_ln + (T - 1) * D;
  for (uint32_t v = 0; v < V; v++) {
    float sum = (int8_t)pgm_read_byte(lm_bias.data + v) * lm_bias.scale;
    for (uint32_t d = 0; d < D; d++) {
      int8_t qv = (int8_t)pgm_read_byte(lm_head.data + (d * V + v));
      sum += lastRow[d] * (qv * lm_head.scale);
    }
    buf_logits[v] = sum;
  }
}

// ==========================================
// 7. SENSES, REFLEXES & HUMAN SKILLS
// ==========================================
void blinkMorse(const String& msg) {
  const char* morseTable[26] = {
    ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---",
    "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-",
    "..-", "...-", ".--", "-..-", "-.--", "--.."
  };
  String upper = msg;
  upper.toUpperCase();
  for (unsigned int i = 0; i < upper.length() && i < 12; i++) {
    char c = upper[i];
    if (c >= 'A' && c <= 'Z') {
      const char* code = morseTable[c - 'A'];
      for (int j = 0; code[j] != '\0'; j++) {
        digitalWrite(LED_PIN, LOW);
        delay(code[j] == '.' ? 90 : 240);
        digitalWrite(LED_PIN, HIGH);
        delay(90);
      }
      delay(180);
    } else if (c == ' ') {
      delay(300);
    }
  }
}

String tryMathSkill(const String& q) {
  String s = q; s.toLowerCase();
  char ops[4] = {'+', '-', '*', '/'};
  for (int k = 0; k < 4; k++) {
    int opIdx = s.indexOf(ops[k]);
    if (opIdx > 0) {
      String left = s.substring(0, opIdx);
      String right = s.substring(opIdx + 1);
      int lStart = left.length() - 1;
      while (lStart >= 0 && (isDigit(left[lStart]) || left[lStart] == '.' || left[lStart] == ' ')) lStart--;
      float a = left.substring(lStart + 1).toFloat();
      float b = right.toFloat();
      if (a != 0.0f || b != 0.0f) {
        float res = 0.0f;
        if (ops[k] == '+') res = a + b;
        else if (ops[k] == '-') res = a - b;
        else if (ops[k] == '*') res = a * b;
        else if (ops[k] == '/') {
          if (b == 0.0f) return "I cannot divide by zero!";
          res = a / b;
        }
        return "I calculated that " + String(a, 2) + " " + String(ops[k]) + " " + String(b, 2) + " equals " + String(res, 2) + ".";
      }
    }
  }
  return "";
}

String matchHumanSkill(const String& query) {
  String q = query; q.toLowerCase();
  for (int i = 0; i < skillCount; i++) {
    if (q.indexOf(skills[i].name) >= 0) {
      return "Here is how I learned to " + skills[i].name + ": " + skills[i].steps;
    }
  }
  return "";
}

String retrieveMemory(const String& query) {
  String q = query; q.toLowerCase();
  String best = "";
  int bestScore = 0;
  for (int i = 0; i < memCount; i++) {
    int sayIdx = memories[i].indexOf("<SAY>");
    if (sayIdx < 0) continue;
    String memLower = memories[i]; memLower.toLowerCase();
    int score = 0;
    int start = 0;
    while (start < (int)q.length()) {
      int sp = q.indexOf(' ', start);
      if (sp < 0) sp = q.length();
      String w = q.substring(start, sp);
      w.replace("?", ""); w.replace(".", ""); w.replace("!", "");
      if (w.length() >= 3 && w != "what" && w != "who" && w != "how" && w != "tell" && w != "about" && w != "the") {
        if (memLower.indexOf(w) >= 0) score++;
      }
      start = sp + 1;
    }
    if (score >= bestScore && score > 0) {
      bestScore = score;
      best = memories[i];
    }
  }
  return best;
}

String generate(const String& userPrompt, int maxNew = 24, float temp = 0.45f) {
  String mem = retrieveMemory(userPrompt);
  String fullPrompt = (mem.length() > 0) ? (mem + "\n<USER> " + userPrompt + " <THINK>")
                                         : ("<USER> " + userPrompt + " <THINK>");
  int ids[MAX_SEQ_LEN];
  int T = tokenize(fullPrompt, ids, MAX_SEQ_LEN - 1);
  if (T == 0) { ids[0] = findToken("<THINK>"); T = 1; }

  String rawOut = "";
  int nlId = findToken("\n");

  for (int step = 0; step < maxNew; step++) {
    int ctxLen = (T < MAX_SEQ_LEN) ? T : MAX_SEQ_LEN;
    forwardStep(ids + (T - ctxLen), ctxLen);

    int topIds[4] = {0, 0, 0, 0};
    float topVals[4] = {-1e9f, -1e9f, -1e9f, -1e9f};
    for (uint32_t v = 2; v < V; v++) {
      float val = buf_logits[v] / temp;
      for (int k = 0; k < 4; k++) {
        if (val > topVals[k]) {
          for (int m = 3; m > k; m--) { topVals[m] = topVals[m - 1]; topIds[m] = topIds[m - 1]; }
          topVals[k] = val; topIds[k] = (int)v;
          break;
        }
      }
    }

    float probs[4];
    float sumP = 0.0f;
    for (int k = 0; k < 4; k++) { probs[k] = expf(topVals[k] - topVals[0]); sumP += probs[k]; }
    float r = ((float)random(0, 10000) / 10000.0f) * sumP;
    int chosen = topIds[0];
    float acc = 0.0f;
    for (int k = 0; k < 4; k++) {
      acc += probs[k];
      if (r <= acc) { chosen = topIds[k]; break; }
    }

    if (chosen == nlId) break;
    if (T < MAX_SEQ_LEN) ids[T++] = chosen;
    else {
      for (int i = 1; i < MAX_SEQ_LEN; i++) ids[i - 1] = ids[i];
      ids[MAX_SEQ_LEN - 1] = chosen;
    }

    String tok = vocab[chosen];
    if (tok == "." || tok == "," || tok == "!" || tok == "?") rawOut += tok;
    else rawOut += " " + tok;

    int sayCheck = rawOut.indexOf("<SAY>");
    if (sayCheck >= 0) {
      String afterSay = rawOut.substring(sayCheck + 5);
      afterSay.trim();
      if (afterSay.length() > 6 && (tok == "." || tok == "!" || tok == "?")) {
        break;
      }
      if (tok.startsWith("<") && tok != "<SAY>") {
        break;
      }
    }
  }

  int sayPos = rawOut.indexOf("<SAY>");
  if (sayPos >= 0) rawOut = rawOut.substring(sayPos + 5);
  else {
    int askPos = rawOut.indexOf("<ASK>");
    if (askPos >= 0) rawOut = rawOut.substring(askPos + 5);
  }
  rawOut.replace("<USER>", "");
  rawOut.replace("<THINK>", "");
  rawOut.replace("<SAY>", "");
  rawOut.replace("<ASK>", "");
  rawOut.replace("<EXPLORE>", "");
  rawOut.trim();
  if (rawOut.length() == 0) rawOut = "I am still learning English! Tell me more.";
  return rawOut;
}

// ==========================================
// 8. WIKIPEDIA EXPLORER & SKILL LEARNER
// ==========================================
String extractJsonField(const String& json, const String& key) {
  String pattern = "\"" + key + "\":\"";
  int start = json.indexOf(pattern);
  if (start < 0) return "";
  start += pattern.length();
  String result = "";
  bool escaped = false;
  for (int i = start; i < (int)json.length(); i++) {
    char c = json[i];
    if (escaped) {
      if (c == 'n') result += ' ';
      else result += c;
      escaped = false;
    } else if (c == '\\') {
      escaped = true;
    } else if (c == '"') {
      break;
    } else {
      result += c;
    }
  }
  return result;
}

String exploreWikipedia(const String& topic = "", bool asSkill = false) {
  if (!wifiConnected || WiFi.status() != WL_CONNECTED) {
    return "I need a 2.4GHz Wi-Fi connection before I can browse Wikipedia!";
  }
  HTTPClient http;
  String url = "https://en.wikipedia.org/api/rest_v1/page/random/summary";
  if (topic.length() > 0) {
    String clean = topic; clean.trim(); clean.replace(" ", "_");
    url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + clean;
  }
  http.begin(url);
  http.setUserAgent("XIAOS3SAMTransformer/1.0");
  http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
  int code = http.GET();
  if (code != 200) {
    http.end();
    return "Could not fetch Wikipedia right now (HTTP " + String(code) + ").";
  }
  String payload = http.getString();
  http.end();

  String title = extractJsonField(payload, "title");
  String extract = extractJsonField(payload, "extract");
  if (title.length() == 0 || extract.length() < 20) return "Article had too little text.";

  int dotIdx = extract.indexOf('.');
  String firstSentence = (dotIdx > 10) ? extract.substring(0, dotIdx + 1) : extract.substring(0, 120);

  if (asSkill) {
    learnSkill(title, firstSentence, true);
    return "I studied " + title + " on Wikipedia and added it to my human skills!";
  } else {
    addMemory("<USER> What is " + title + " ? <THINK> Learned on Wi-Fi . <SAY> " + firstSentence, true);
    return "I just read about " + title + ": " + firstSentence;
  }
}

// ==========================================
// 9. WEB CHAT SERVER & INPUT HANDLER
// ==========================================
const char HTML_PAGE[] PROGMEM = R"rawliteral(
<!DOCTYPE html><html><head><meta name='viewport' content='width=device-width,initial-scale=1'>
<title>XIAO ESP32S3 SAM AI</title>
<style>body{font-family:sans-serif;background:#111;color:#eee;max-width:600px;margin:auto;padding:15px}
#log{height:360px;overflow-y:auto;border:1px solid #333;padding:10px;background:#1a1a1a;border-radius:8px;margin-bottom:10px}
input{width:76%;padding:10px;border-radius:6px;border:1px solid #444;background:#222;color:#fff}
button{width:20%;padding:10px;border-radius:6px;border:none;background:#0a84ff;color:#fff;font-weight:bold}</style></head>
<body><h3>XIAO ESP32S3 SAM Transformer</h3>
<div id='log'><p><i>Try: hello, /say i am sam, /pitch 55, /speed 80, /skills, /teach name : steps</i></p></div>
<input id='m' placeholder='Say something...' onkeydown='if(event.key==="Enter")send()'>
<button onclick='send()'>Send</button>
<script>async function send(){let i=document.getElementById('m');let v=i.value;if(!v)return;i.value='';
let l=document.getElementById('log');l.innerHTML+='<p><b>You:</b> '+v+'</p>';
let r=await fetch('/chat?msg='+encodeURIComponent(v));let t=await r.text();
l.innerHTML+='<p style="color:#5ac8fa"><b>AI:</b> '+t+'</p>';l.scrollTop=l.scrollHeight;}</script></body></html>
)rawliteral";

String processInput(String msg) {
  msg.trim();
  if (msg.length() == 0) return "";
  lastInteractionTime = millis();
  String lower = msg; lower.toLowerCase();

  if (lower == "/mute") { voiceEnabled = false; return "Voice muted."; }
  if (lower == "/voice") {
    voiceEnabled = true;
    speakSAM("Voice enabled.");
    return "SAM voice enabled!";
  }
  if (lower.startsWith("/say ")) {
    String phrase = msg.substring(5);
    speakSAM(phrase);
    return "SAM spoke: " + phrase;
  }
  if (lower.startsWith("/pitch ")) {
    samPitch = constrain(msg.substring(7).toInt(), 30, 140);
    speakSAM("Pitch updated.");
    return "SAM pitch set to " + String(samPitch) + " (lower = deeper).";
  }
  if (lower.startsWith("/speed ")) {
    samSpeed = constrain(msg.substring(7).toInt(), 40, 130);
    speakSAM("Speed updated.");
    return "SAM speed set to " + String(samSpeed) + " (lower = faster).";
  }
  if (lower == "/skills") {
    String out = "Human Skills (" + String(skillCount) + "): ";
    for (int i = 0; i < skillCount; i++) out += "[" + skills[i].name + "] ";
    return out;
  }
  if (lower.startsWith("/teach ")) {
    int sep = msg.indexOf(':');
    if (sep > 7) {
      String sName = msg.substring(7, sep);
      String sSteps = msg.substring(sep + 1);
      learnSkill(sName, sSteps, true);
      speakSAM("I learned " + sName);
      return "Learned new human skill '" + sName + "' and saved to flash!";
    }
    return "Format: /teach skill name : step 1, step 2...";
  }
  if (lower.startsWith("/learnskill ")) {
    String res = exploreWikipedia(msg.substring(12), true);
    speakSAM(res);
    return res;
  }
  if (lower == "/explore") {
    String res = exploreWikipedia("", false);
    speakSAM(res);
    return res;
  }
  if (lower == "/memories") {
    String out = "Stored Memories (" + String(memCount) + "): ";
    int start = (memCount > 5) ? memCount - 5 : 0;
    for (int i = start; i < memCount; i++) out += "\n- " + memories[i];
    return out;
  }
  if (lower == "/reset") {
    LittleFS.remove("/memories.txt");
    LittleFS.remove("/skills.txt");
    memCount = 0; skillCount = 0;
    initDefaultSkills();
    return "Flash memory cleared and reset to defaults.";
  }

  if (lower.indexOf("how do you feel") >= 0 || lower.indexOf("temperature") >= 0) {
    float tempC = temperatureRead();
    String reply = "My internal silicon temperature is " + String(tempC, 1) + " degrees Celsius. I feel great!";
    speakSAM(reply);
    return reply;
  }
  if (lower.indexOf("blink") >= 0 || lower.indexOf("morse") >= 0 || lower.indexOf("wave") >= 0) {
    blinkMorse("HI");
    String reply = "I blinked hello in Morse code on my onboard LED!";
    speakSAM(reply);
    return reply;
  }

  String mathAns = tryMathSkill(msg);
  if (mathAns.length() > 0) {
    addMemory("<USER> " + msg + " <THINK> Solved math . <SAY> " + mathAns, true);
    speakSAM(mathAns);
    return mathAns;
  }

  String skillAns = matchHumanSkill(msg);
  if (skillAns.length() > 0) {
    speakSAM(skillAns);
    return skillAns;
  }

  if (pendingQuestion.length() > 0) {
    addMemory("<USER> " + pendingQuestion + " <THINK> Human answered me . <SAY> " + msg, true);
    pendingQuestion = "";
  }

  String reply = generate(msg);
  addMemory("<USER> " + msg + " <THINK> Chatting with human . <SAY> " + reply, true);
  speakSAM(reply);
  return reply;
}

void handleRoot() { server.send_P(200, "text/html", HTML_PAGE); }
void handleChat() {
  if (!server.hasArg("msg")) { server.send(400, "text/plain", "Missing msg"); return; }
  String reply = processInput(server.arg("msg"));
  Serial.println("\nYou (Web): " + server.arg("msg"));
  Serial.println("AI: " + reply);
  server.send(200, "text/plain", reply);
}

// ==========================================
// 10. SETUP & NON-BLOCKING MAIN LOOP
// ==========================================
String serialLineBuf = "";

void setup() {
  Serial.begin(115200);
  delay(800);
  while (Serial.available()) Serial.read();

  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);

  Serial.println("\n=== Booting Standard XIAO ESP32S3 SAM Voice Transformer ===");
  loadPersistentStorage();
  if (!loadBrain()) {
    Serial.println("[Fatal] Could not load brain_data.h!");
    while (true) delay(1000);
  }
  Serial.printf("[Senses Ready] Memories: %d | Human Skills: %d\n", memCount, skillCount);

  if (strlen(WIFI_SSID) > 0) {
    WiFi.mode(WIFI_STA);
    WiFi.disconnect(true);
    delay(200);
    WiFi.setTxPower(WIFI_POWER_8_5dBm);
    Serial.printf("Connecting to 2.4GHz Wi-Fi (%s)", WIFI_SSID);
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    int tries = 0;
    while (WiFi.status() != WL_CONNECTED && tries < 25) {
      delay(500); Serial.print("."); tries++;
    }
    if (WiFi.status() == WL_CONNECTED) {
      wifiConnected = true;
      Serial.printf("\n[Wi-Fi Connected] Open Web Chat at: http://%s\n", WiFi.localIP().toString().c_str());
      server.on("/", handleRoot);
      server.on("/chat", handleChat);
      server.begin();
    } else {
      Serial.println("\n[Offline Mode] Wi-Fi skipped; USB Serial chat active.");
    }
  } else {
    Serial.println("[Offline Mode] USB Serial chat active.");
  }

  speakSAM("Hello. I am SAM.");
  lastInteractionTime = millis();
  lastExploreTime = millis();
  Serial.println("Type a message, /say hello, /pitch 64, /speed 72, or /skills!");
}

void loop() {
  if (wifiConnected) server.handleClient();

  while (Serial.available() > 0) {
    char c = (char)Serial.read();
    if (c == '\n' || c == '\r') {
      serialLineBuf.trim();
      if (serialLineBuf.length() > 0) {
        Serial.println("You: " + serialLineBuf);
        String reply = processInput(serialLineBuf);
        Serial.println("AI: " + reply);
      }
      serialLineBuf = "";
    } else if (serialLineBuf.length() < 160) {
      serialLineBuf += c;
    }
  }

  if (millis() - lastInteractionTime > 50000 && pendingQuestion.length() == 0 && memCount > 0) {
    int idx = random(0, memCount);
    int sayPos = memories[idx].indexOf("<SAY>");
    if (sayPos > 0) {
      String snippet = memories[idx].substring(sayPos + 5);
      snippet.trim();
      if (snippet.length() > 35) snippet = snippet.substring(0, 35) + "...";
      pendingQuestion = "I was thinking about: " + snippet + " What do you think?";
      Serial.println("\nAI (Curious): " + pendingQuestion);
      speakSAM("What do you think?");
      lastInteractionTime = millis();
    }
  }

  if (wifiConnected && millis() - lastExploreTime > 120000) {
    lastExploreTime = millis();
    String discovery = exploreWikipedia("", false);
    Serial.println("\n[Autonomous Discovery] " + discovery);
    speakSAM("I learned something new.");
  }

  delay(5);
}
```
