<?php
veja isso:
<?php
// Vocabulário (token => índice)
$vocab = [
'<pad>' => 0,
'olá' => 1,
'mundo' => 2,
'eu' => 3,
'sou' => 4,
'GPT' => 5,
'e' => 6,
'gosto' => 7,
'de' => 8,
'php' => 9,
'.' => 10,
];
// Vetores embedding 4D para cada token (valores fictícios)
$embeddings = [
[0, 0, 0, 0], // <pad>
[1, 0, 0, 0], // olá
[0, 1, 0, 0], // mundo
[0, 0, 1, 0], // eu
[1, 1, 0, 0], // sou
[1, 0, 1, 0], // GPT
[0, 1, 1, 0], // e
[1, 1, 1, 0], // gosto
[0, 0, 0, 1], // de
[1, 0, 0, 1], // php
[0, 0, 0, 0.5], // .
];
// Matriz 4x4 de "atenção" fictícia (pesos)
$attn_weights = [
[0.4, 0.3, 0.2, 0.1],
[0.1, 0.5, 0.3, 0.1],
[0.2, 0.2, 0.5, 0.1],
[0.3, 0.1, 0.1, 0.5],
];
// Função softmax
function softmax(array $x): array {
$max = max($x);
$exps = array_map(fn($v) => exp($v - $max), $x); // estabilidade numérica
$sum = array_sum($exps);
return array_map(fn($v) => $v / $sum, $exps);
}
// Multiplica matriz por vetor
function mat_vec_mul(array $mat, array $vec): array {
$result = [];
foreach ($mat as $row) {
$sum = 0;
for ($i = 0; $i < count($vec); $i++) {
$sum += $row[$i] * $vec[$i];
}
$result[] = $sum;
}
return $result;
}
// Escolhe token baseado em probabilidades (amostragem)
function sample_token(array $probs): int {
$r = mt_rand() / mt_getrandmax(); // número entre 0 e 1
$cumulative = 0.0;
foreach ($probs as $i => $p) {
$cumulative += $p;
if ($r <= $cumulative) {
return $i;
}
}
// fallback
return count($probs) - 1;
}
// Gera próximo token baseado no token atual
function next_token(int $current_token, array $embeddings, array $attn_weights): int {
$input_vec = $embeddings[$current_token];
$attn_out = mat_vec_mul($attn_weights, $input_vec);
$probs = softmax($attn_out);
return sample_token($probs);
}
// Gera texto a partir de token inicial
function generate_text(int $start_token, int $length, array $vocab, array $embeddings, array $attn_weights): string {
$idx2token = array_flip($vocab);
$current_token = $start_token;
$output_tokens = [];
for ($i = 0; $i < $length; $i++) {
$output_tokens[] = $idx2token[$current_token];
$current_token = next_token($current_token, $embeddings, $attn_weights);
}
return implode(' ', $output_tokens);
}
// --- Exemplo de uso ---
$start_token = $vocab['olá'];
$generated = generate_text($start_token, 10, $vocab, $embeddings, $attn_weights);
echo "Texto gerado:\n$generated\n";