Skip to content

Laravel examples

Short, realistic examples of training and serving models with Talario inside a Laravel application.

These show the shape of day-to-day use, and running them needs a Talario build. More programs are under Examples.

An in-process inference endpoint

use Talario\InferenceService;

// InferenceService is bound as a singleton (see "Talario for Laravel"), so the
// model stays warm across requests.
public function predict(Request $request, InferenceService $model)
{
    $data = $request->validate([
        'features'   => ['required', 'array', 'size:64'],
        'features.*' => ['numeric'],
    ]);

    return response()->json([
        'logits' => $model->infer($data['features']),   // warm model, no reload, no IPC
    ]);
}

A queued training job

use Talario\Device;
use Talario\Tape;
use Talario\Linear;
use Talario\Sequential;
use Talario\SGD;
use function Talario\relu;

class TrainClassifier implements ShouldQueue
{
    public function handle(): void
    {
        $dev = new Device('auto');                     // 'cpu' | 'gpu' | 'auto'
        $net = new Sequential([
            new Linear($dev, 2, 16, seed: 1), relu(),
            new Linear($dev, 16, 3, seed: 2),
        ]);
        $opt = new SGD($net->parameters(), lr: 0.2);

        [$X, $Y, $n] = $this->dataset();               // features [n,2], one-hot labels [n,3]

        for ($epoch = 0; $epoch <= 300; $epoch++) {
            $t      = new Tape($dev);
            $logits = $net($t, $t->tensor($X, [$n, 2]));
            $loss   = $t->softmaxCrossEntropy($logits, $t->tensor($Y, [$n, 3]));
            $t->backward($loss);
            $opt->step();
        }

        // Persist the trained weights so the warm InferenceService can load them.
    }
}

Returning a prediction

$logits = $model->infer($features);          // plain PHP array of class logits
$label  = array_keys($logits, max($logits))[0];

return response()->json(['label' => $label, 'logits' => $logits]);

Built something with Talario and Laravel? Add it to the showcase.

Using a coding agent?

Copy a prompt for Laravel integration, with 2 exact API signatures.