83 lines
2.3 KiB
PHP
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));
|
|
}
|
|
}
|
|
}
|