Files
perceptron-viewer/app/Services/IterationEventBuffer/PerceptronLimitedEpochEventBuffer.php
T
Ninluc 69e683bcaf
linter / quality (push) Successful in 4m24s
tests / ci (8.4) (push) Successful in 4m47s
tests / ci (8.5) (push) Successful in 5m0s
Some bugfixes and misc
2026-09-08 20:01:52 +02:00

83 lines
2.3 KiB
PHP

<?php
namespace App\Services\IterationEventBuffer;
use App\Events\PerceptronTrainingIteration;
class PerceptronLimitedEpochEventBuffer implements IPerceptronIterationEventBuffer
{
private array $data = [];
private ?int $activeEpoch = null;
private bool $shouldBroadcastEpoch = false;
private ?float $lastBroadcastAt = null;
public function __construct(
private string $sessionId,
private string $trainingId,
private int $epochInterval,
) {}
public function flush(): void
{
if ($this->data === []) {
return;
}
$this->waitForBroadcastInterval();
event(new PerceptronTrainingIteration($this->data, $this->sessionId, $this->trainingId));
$this->lastBroadcastAt = microtime(true);
$this->data = [];
}
public function addIteration(int $epoch, int $exampleIndex, float $error, array $synaptic_weights): void
{
$newData = [
'epoch' => $epoch,
'exampleIndex' => $exampleIndex,
'error' => $error,
'weights' => $synaptic_weights,
];
if ($this->activeEpoch !== $epoch) {
$this->flush();
$this->activeEpoch = $epoch;
$this->shouldBroadcastEpoch = $epoch === 1 || $epoch % $this->epochInterval === 0;
}
if (! $this->shouldBroadcastEpoch) {
return;
}
$this->data[] = $newData;
if ($this->payloadExceedsLimit() || count($this->data) >= config('perceptron.broadcast_iteration_size')) {
$this->flush();
}
}
private function payloadExceedsLimit(): bool
{
return strlen(json_encode([
'iterations' => PerceptronTrainingIteration::normalizeForJson($this->data),
'trainingId' => $this->trainingId,
], JSON_THROW_ON_ERROR)) > config('broadcasting.broadcast_max_payload_size');
}
private function waitForBroadcastInterval(): void
{
if ($this->lastBroadcastAt === null) {
return;
}
$minimumInterval = config('perceptron.broadcast_minimum_interval_ms') / 1000;
$remainingInterval = $minimumInterval - (microtime(true) - $this->lastBroadcastAt);
if ($remainingInterval > 0) {
usleep((int) ceil($remainingInterval * 1_000_000));
}
}
}