65 lines
1.7 KiB
PHP
65 lines
1.7 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;
|
|
|
|
public function __construct(
|
|
private string $sessionId,
|
|
private string $trainingId,
|
|
private int $epochInterval,
|
|
) {}
|
|
|
|
public function flush(): void
|
|
{
|
|
if ($this->data === []) {
|
|
return;
|
|
}
|
|
|
|
event(new PerceptronTrainingIteration($this->data, $this->sessionId, $this->trainingId));
|
|
$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' => $this->data,
|
|
'trainingId' => $this->trainingId,
|
|
], JSON_THROW_ON_ERROR)) > config('broadcasting.broadcast_max_payload_size');
|
|
}
|
|
}
|