Arpan Tripathi
add metagraph resync & alpha stake finalisation in competitions' enrolling phase (#189)
4758a24 unverified Download neurons/validator.py from silvanus0930/vidaio-subnet: direct link, hf CLI and curl.
- Browser
- Download file 124 kB
-
https://huggingface.co/silvanus0930/vidaio-subnet/resolve/main/neurons/validator.py
- Command line
-
hf download hf://silvanus0930/vidaio-subnet/neurons/validator.py
-
curl -L -o validator.py https://huggingface.co/silvanus0930/vidaio-subnet/resolve/main/neurons/validator.py
124 kB
import os
import argparse
import time
import uuid
import httpx
import random
import asyncio
import traceback
import pandas as pd
import bittensor as bt
import tempfile
import aiohttp
import ipaddress
import math
from loguru import logger
from dotenv import load_dotenv
from datetime import datetime, timezone
from concurrent.futures import ThreadPoolExecutor
from vidaio_subnet_core.utilities.version import get_version
from vidaio_subnet_core.utilities.storage_client import storage_client
from vidaio_subnet_core import validating, CONFIG, base, protocol
from vidaio_subnet_core.base.config import add_common_config
from vidaio_subnet_core.utilities.wandb_manager import WandbManager
from services.video_scheduler.video_utils import get_trim_video_path, get_perumted_video_path
from vidaio_subnet_core.utilities.uids import get_organic_forward_uids
from vidaio_subnet_core.protocol import (
LengthCheckProtocol,
TaskWarrantProtocol,
TaskType,
VideoCompressionJobProtocol,
VideoCompressionPollProtocol,
VideoUpscalingJobProtocol,
VideoUpscalingPollProtocol,
MinerResponse,
CompetitionInvitationProtocol,
CompetitionSubmissionProtocol,
)
from vidaio_subnet_core.competition.config import (
CompetitionConfig,
CompetitionManifest,
)
from vidaio_subnet_core.competition.artifact_backup import (
CompetitionArtifactBackupError,
CompetitionArtifactBackupService,
CompetitionDatabaseBackupError,
)
from vidaio_subnet_core.competition.build import (
CompetitionBuildService,
ModalImageBuildBackend,
ModalImageBuilder,
)
from vidaio_subnet_core.competition.enrollment import (
CompetitionEnrollmentDispatcher,
CompetitionMinerEndpoint,
)
from vidaio_subnet_core.competition.intake import (
CompetitionSubmissionIntakeService,
RepositoryIntake,
)
from vidaio_subnet_core.competition.manager import CompetitionManager
from vidaio_subnet_core.competition.execution import CompetitionExecutionCoordinator
from vidaio_subnet_core.competition.dataset import ModalVolumeStore
from vidaio_subnet_core.competition.scoring_api import CompetitionScoringClient
from vidaio_subnet_core.competition.modal_runner import (
CompetitionModalRunner,
ModalSandboxBackend,
)
from vidaio_subnet_core.competition.repository import CompetitionRepository
from vidaio_subnet_core.competition.state import CompetitionState
from vidaio_subnet_core.validating.managing.sql_schemas import MinerMetadata, MinerPerformanceHistory, Base
from sqlalchemy import desc, asc, func, select, delete
from sqlalchemy.ext.asyncio import AsyncSession
from datetime import datetime, timedelta
from services.dashboard.server import send_upscaling_data_to_dashboard, send_compression_data_to_dashboard
from services.scoring.compression_score_cache import (
CompressionScoreCache,
find_duplicate_compression_scores,
)
from services.scoring.artifact_cleanup import cleanup_compression_artifacts
from services.video_scheduler.redis_utils import (
get_redis_connection,
get_organic_upscaling_queue_size,
get_organic_compression_queue_size,
set_scheduler_ready
)
from typing import List, Tuple, Any
from enum import Enum, IntEnum
load_dotenv()
METAGRAPH_REFRESH_INTERVAL_SECONDS = float(
os.getenv("METAGRAPH_REFRESH_INTERVAL_SECONDS", 30 * 60)
)
class VMAF_QUALITY_THRESHOLD(IntEnum):
LOW = 85
MEDIUM = 89
HIGH = 93
TARGET_CODECS = [
"av1", # AV1 codec (protocol standard name)
"hevc", # H.265/HEVC (protocol standard name)
# "h264", # H.264/AVC (protocol standard name)
# "vp9", # VP9 (protocol standard name)
]
# Codec encoding modes
CODEC_MODES = [
"CRF", # Constant Rate Factor (quality-based)
"VBR", # Variable Bitrate
]
# Target bitrates in Mbps for CBR/VBR modes
TARGET_BITRATES = [
5.0, # 5 Mbps
8.0, # 8 Mbps
10.0, # 10 Mbps
]
SLEEP_TIME_LOW = 60 * 5 # 5 minutes
SLEEP_TIME_HIGH = 60 * 6 # 6 minutes
try:
SYNTHETIC_QUERIES_PER_MINER = max(1, int(os.getenv("SYNTHETIC_QUERIES_PER_MINER", "5")))
except ValueError:
logger.warning("Invalid SYNTHETIC_QUERIES_PER_MINER value, defaulting to 5")
SYNTHETIC_QUERIES_PER_MINER = 5
UPSCALING_SCORING_BATCH_SIZE = 5
COMPRESSION_SCORING_BATCH_SIZE = 5
try:
ORGANIC_QUERIES_PER_MINER = max(
1, int(os.getenv("ORGANIC_QUERIES_PER_MINER", str(SYNTHETIC_QUERIES_PER_MINER)))
)
except ValueError:
logger.warning("Invalid ORGANIC_QUERIES_PER_MINER value, defaulting to SYNTHETIC_QUERIES_PER_MINER")
ORGANIC_QUERIES_PER_MINER = SYNTHETIC_QUERIES_PER_MINER
class ValidatorMode(str, Enum):
INFERENCE = "inference"
COMPETITION = "competition"
class Validator(base.BaseValidator):
def get_config(self):
parser = add_common_config(argparse.ArgumentParser())
parser.add_argument(
"--validator-mode",
choices=[mode.value for mode in ValidatorMode],
default=ValidatorMode.INFERENCE.value,
help="Run only inference loops or only the competition scheduler.",
)
config = bt.Config(parser)
config.full_path = os.path.expanduser(
os.path.join(
config.logging.logging_dir,
config.wallet.name,
config.wallet.hotkey,
f"netuid{config.netuid}",
"validator",
config.validator_mode,
)
)
os.makedirs(config.full_path, exist_ok=True)
return config
def setup_axon(self):
if self.config.validator_mode == ValidatorMode.COMPETITION.value:
self.axon = None
logger.info("Competition process does not start a validator Axon")
return
super().setup_axon()
def __init__(self):
self._last_metagraph_refresh_monotonic: float | None = None
super().__init__()
self.validator_mode = ValidatorMode(self.config.validator_mode)
logger.info("Starting validator in {} mode", self.validator_mode.value)
self.miner_manager = None
self.challenge_synthesizer = None
self.score_client_upscaling = None
self.score_client_compression = None
self.score_client_upscaling_organics = None
self.score_client_compression_organics = None
self.set_weights_executor = None
self.redis_conn = None
self.wandb_manager = None
self.competition_score_client: CompetitionScoringClient | None = None
self.competition_config = (
CompetitionConfig()
if self.validator_mode is ValidatorMode.COMPETITION
else CompetitionConfig(
mode_enabled=False,
execution_enabled=False,
build_backend="disabled",
)
)
self.competition_rewards_repository: CompetitionRepository | None = None
if self.validator_mode is ValidatorMode.INFERENCE:
competition_database_url = os.getenv(
"COMPETITION_DATABASE_URL", ""
).strip()
if competition_database_url:
self.competition_rewards_repository = CompetitionRepository(
competition_database_url
)
logger.info(
"Inference weights will read competition rankings from {}",
competition_database_url,
)
else:
logger.info(
"Competition rewards disabled in inference mode: "
"COMPETITION_DATABASE_URL is not set"
)
self._initialize_inference_services()
else:
self.wandb_manager = WandbManager(
validator=self,
run_suffix="-competition",
)
logger.info("π Initialized competition Wandb Manager π")
self.competition_repository: CompetitionRepository | None = None
self.competition_dispatcher: CompetitionEnrollmentDispatcher | None = None
self.competition_execution_coordinator: (
CompetitionExecutionCoordinator | None
) = None
self.competition_artifact_backup: (
CompetitionArtifactBackupService | None
) = None
if self.competition_config.mode_enabled:
competition_repository = CompetitionRepository(
self.competition_config.database_url
)
self.competition_repository = competition_repository
self.competition_manager = CompetitionManager(
self.competition_config,
competition_repository,
)
logger.info(
"Competition mode enabled: scheduler_interval={}s manifest_glob={!r} "
"artifact_root={} network_timeout={}s max_concurrent_requests={}",
self.competition_config.scheduler_interval_seconds,
self.competition_config.manifest_glob,
self.competition_config.artifact_root,
self.competition_config.network_timeout_seconds,
self.competition_config.max_concurrent_requests,
)
else:
self.competition_manager = CompetitionManager(self.competition_config)
logger.info("Competition scheduler disabled (COMPETITION_MODE_ENABLED=false)")
if self.competition_repository is not None:
self.competition_artifact_backup = CompetitionArtifactBackupService(
self.competition_repository,
artifact_root=self.competition_config.artifact_root,
bucket=self.competition_config.artifact_backup_bucket,
key_prefix=self.competition_config.artifact_backup_prefix,
region_name=self.competition_config.artifact_backup_region,
endpoint_url=self.competition_config.artifact_backup_endpoint_url,
access_key_id=(
self.competition_config.artifact_backup_access_key_id
),
secret_access_key=(
self.competition_config.artifact_backup_secret_access_key
),
database_url=self.competition_config.database_url,
actor=self.competition_config.owner_id,
)
self.competition_artifact_backup.preflight_privacy()
competition_intake = CompetitionSubmissionIntakeService(
RepositoryIntake(self.competition_config.artifact_root),
self.competition_repository,
)
self.competition_dispatcher = CompetitionEnrollmentDispatcher(
self.competition_repository,
competition_intake,
self._forward_competition_request,
owner_id=self.competition_config.owner_id,
timeout_seconds=self.competition_config.network_timeout_seconds,
max_concurrent_requests=(
self.competition_config.max_concurrent_requests
),
)
logger.info(
"Competition enrollment dispatcher initialized: timeout={}s "
"max_concurrent_requests={}",
self.competition_config.network_timeout_seconds,
self.competition_config.max_concurrent_requests,
)
if self.competition_config.execution_enabled:
accepted_build_statuses = frozenset(
{"MODAL_ACCEPTED", "DEVELOPMENT_ACCEPTED"}
)
modal_build_backend = ModalImageBuildBackend(
environment_name=self.competition_config.modal_environment
)
build_service = CompetitionBuildService(
self.competition_repository,
ModalImageBuilder(modal_build_backend),
actor=self.competition_config.owner_id,
accepted_build_status="MODAL_ACCEPTED",
)
sandbox_runner = CompetitionModalRunner(
self.competition_repository,
ModalSandboxBackend(
environment_name=self.competition_config.modal_environment
),
actor=self.competition_config.owner_id,
accepted_build_statuses=accepted_build_statuses,
)
competition_score_url = (
f"http://{CONFIG.score.host}:"
f"{CONFIG.score.compression_competition_score_port}"
)
self.competition_score_client = CompetitionScoringClient(
competition_score_url,
modal_environment=self.competition_config.modal_environment,
)
self.competition_execution_coordinator = (
CompetitionExecutionCoordinator(
self.competition_manager,
self.competition_repository,
build_service,
sandbox_runner,
artifact_root=self.competition_config.artifact_root,
actor=self.competition_config.owner_id,
accepted_build_statuses=accepted_build_statuses,
dataset_store=ModalVolumeStore(
environment_name=(
self.competition_config.modal_environment
)
),
item_scorer=self.competition_score_client,
defer_round_commit=True,
)
)
logger.warning(
"Competition execution enabled with direct Modal builds: "
"environment={} operator acknowledged that Modal does not "
"attest the 25 GB final-image size limit; scoring_endpoint={}",
self.competition_config.modal_environment,
competition_score_url,
)
def _initialize_inference_services(self) -> None:
self.miner_manager = validating.managing.MinerManager(
uid=self.uid,
config=self.config,
wallet=self.wallet,
metagraph=self.metagraph,
subtensor=self.subtensor,
competition_repository=self.competition_rewards_repository,
)
logger.info("π§ Initialized miner manager π§")
self.challenge_synthesizer = validating.synthesizing.Synthesizer()
logger.info("π§ Initialized challenge synthesizer π§")
self.score_client_upscaling = httpx.AsyncClient(
base_url=f"http://{CONFIG.score.host}:{CONFIG.score.upscaling_score_port}"
)
logger.info(
f"π§ Initialized upscaling score client with base URL: http://{CONFIG.score.host}:{CONFIG.score.upscaling_score_port} π§"
)
self.score_client_compression = httpx.AsyncClient(
base_url=f"http://{CONFIG.score.host}:{CONFIG.score.compression_score_port}"
)
logger.info(
f"π§ Initialized compression score client with base URL: http://{CONFIG.score.host}:{CONFIG.score.compression_score_port} π§"
)
self.score_client_upscaling_organics = httpx.AsyncClient(
base_url=f"http://{CONFIG.score.host}:{CONFIG.score.upscaling_organics_score_port}"
)
logger.info(
f"π§ Initialized organic upscaling score client with base URL: http://{CONFIG.score.host}:{CONFIG.score.upscaling_organics_score_port} π§"
)
self.score_client_compression_organics = httpx.AsyncClient(
base_url=f"http://{CONFIG.score.host}:{CONFIG.score.compression_organics_score_port}"
)
logger.info(
f"π§ Initialized organic compression score client with base URL: http://{CONFIG.score.host}:{CONFIG.score.compression_organics_score_port} π§"
)
self.set_weights_executor = ThreadPoolExecutor(max_workers=1)
logger.info("π Initialized setting weights executor π")
self.redis_conn = get_redis_connection()
logger.info("π Initialized Redis connection π")
self.wandb_manager = WandbManager(validator=self)
logger.info("π Initialized Wandb Manager π")
self.organic_gateway_base_url = f"http://localhost:{CONFIG.organic_gateway.port}"
self.push_result_endpoint = f"http://{CONFIG.video_scheduler.host}:{CONFIG.video_scheduler.port}/api/push_result"
self.scheduler_ready_endpoint = f"http://{CONFIG.video_scheduler.host}:{CONFIG.video_scheduler.port}/api/scheduler_ready"
self.synthetic_deduped_uid_reasons: dict[int, str] = {}
self.synthetic_deduped_uid_sources: dict[int, int] = {}
async def run_competition(self) -> None:
"""Run the independent, restart-safe competition scheduler task."""
if not self.competition_manager.enabled:
return
logger.info("Starting competition scheduler task")
await self.competition_manager.run(
before_finalization=self._finalize_competition_alpha_stake_eligibility,
after_tick=self._run_competition_tick_work,
)
async def close(self) -> None:
clients = (
self.score_client_upscaling,
self.score_client_compression,
self.score_client_upscaling_organics,
self.score_client_compression_organics,
self.competition_score_client,
)
for client in clients:
if client is not None:
await client.aclose()
if self.set_weights_executor is not None:
self.set_weights_executor.shutdown(wait=False, cancel_futures=True)
if self.competition_rewards_repository is not None:
self.competition_rewards_repository.engine.dispose()
async def _run_competition_tick_work(self) -> None:
await self._backup_completed_competition_databases()
await asyncio.to_thread(self.resync_metagraph)
await self._dispatch_competition_enrollment()
backup_ready = await self._backup_finalized_submission_artifacts()
if self.competition_execution_coordinator is not None:
if backup_ready:
await self.competition_execution_coordinator.run_once()
def resync_metagraph(self) -> bool:
"""Refresh all metagraph vectors, including alpha stake, on one cadence."""
now = time.monotonic()
last_refresh = self._last_metagraph_refresh_monotonic
if (
last_refresh is not None
and now - last_refresh < METAGRAPH_REFRESH_INTERVAL_SECONDS
):
return False
logger.info(
"Refreshing validator metagraph (interval={}s); this "
"refreshes alpha-stake values used for competition eligibility",
METAGRAPH_REFRESH_INTERVAL_SECONDS,
)
super().resync_metagraph()
self._last_metagraph_refresh_monotonic = time.monotonic()
return True
def _finalize_competition_alpha_stake_eligibility(
self, competition, now: datetime
) -> None:
"""Reject ineligible submissions immediately before finalisation."""
self.resync_metagraph()
manifest = CompetitionManifest.model_validate_json(competition.manifest_json)
alpha_stakes = {
str(hotkey): (uid, self._competition_alpha_stake(uid))
for uid, hotkey in enumerate(self.metagraph.hotkeys)
}
rejected = self.competition_repository.reject_ineligible_contenders(
competition.competition_id,
alpha_stakes,
manifest.minimum_alpha_stake,
now=now,
)
logger.info(
"Competition alpha-stake eligibility finalized: id={} rejected={}",
competition.competition_id,
rejected,
)
async def _backup_finalized_submission_artifacts(self) -> bool:
if (
self.competition_repository is None
or self.competition_artifact_backup is None
):
return True
competitions = await asyncio.to_thread(
self.competition_repository.list_nonterminal
)
finalizing = [
competition
for competition in competitions
if competition.status
== CompetitionState.FINALIZING_SUBMISSIONS.value
]
ready = True
for competition in finalizing:
if competition.submission_backup_status == "COMPLETED":
continue
try:
result = await asyncio.to_thread(
self.competition_artifact_backup.backup,
competition.competition_id,
)
except CompetitionArtifactBackupError as exc:
ready = False
logger.error(
"Competition submission snapshot backup failed: id={} reason={}",
competition.competition_id,
str(exc),
)
else:
logger.info(
"Competition private submission backup files: id={} "
"archive={} inventory={} database_archive_path={}",
competition.competition_id,
result.archive_s3_uri,
result.inventory_s3_uri,
result.database_archive_path,
)
return ready
async def _backup_completed_competition_databases(self) -> None:
if (
self.competition_repository is None
or self.competition_artifact_backup is None
):
return
competitions = await asyncio.to_thread(
self.competition_repository.list_completed_pending_database_backup
)
for competition in competitions:
try:
result = await asyncio.to_thread(
self.competition_artifact_backup.backup_database,
competition.competition_id,
)
except CompetitionDatabaseBackupError as exc:
logger.error(
"Completed competition database backup failed: id={} reason={}",
competition.competition_id,
str(exc),
)
else:
logger.info(
"Completed competition database backup path: id={} path={}",
competition.competition_id,
result.s3_uri,
)
async def _forward_competition_request(
self,
endpoint: CompetitionMinerEndpoint,
synapse: CompetitionInvitationProtocol | CompetitionSubmissionProtocol,
timeout_seconds: float,
):
responses = await self.dendrite.forward(
axons=[endpoint.transport],
synapse=synapse,
timeout=timeout_seconds,
)
return responses[0] if responses else None
async def _dispatch_competition_enrollment(self) -> None:
if (
self.competition_repository is None
or self.competition_dispatcher is None
):
return
competitions = await asyncio.to_thread(
self.competition_repository.list_nonterminal
)
enrolling = [
competition
for competition in competitions
if competition.status == CompetitionState.ENROLLING.value
]
if not enrolling:
return
endpoints = self._competition_miner_endpoints()
for competition in enrolling:
await self.competition_dispatcher.run_once(competition, endpoints)
def _competition_miner_endpoints(self) -> list[CompetitionMinerEndpoint]:
"""Snapshot registered, serving miner axons without touching inference state."""
endpoints: list[CompetitionMinerEndpoint] = []
min_stake = float(CONFIG.bandwidth.min_stake)
for uid, hotkey in enumerate(self.metagraph.hotkeys):
if uid == self.uid or uid >= len(self.metagraph.axons):
continue
try:
if float(self.metagraph.S[uid]) >= min_stake:
continue
except (IndexError, TypeError, ValueError):
logger.warning(
"Skipping competition invitation candidate UID {}: invalid stake snapshot",
uid,
)
continue
axon = self.metagraph.axons[uid]
is_serving = getattr(axon, "is_serving", True)
if callable(is_serving):
try:
is_serving = is_serving()
except Exception:
is_serving = False
if not is_serving:
continue
endpoints.append(
CompetitionMinerEndpoint(
uid=uid,
hotkey=str(hotkey),
coldkey=self._uid_coldkey(uid) or None,
transport=axon,
alpha_stake=self._competition_alpha_stake(uid),
)
)
logger.debug(
"Competition metagraph snapshot contains {} serving miner endpoint(s)",
len(endpoints),
)
return endpoints
def _competition_alpha_stake(self, uid: int) -> float | None:
for attribute in ("alpha_stake", "AS"):
values = getattr(self.metagraph, attribute, None)
if values is None:
continue
try:
value = values[uid]
tao = getattr(value, "tao", None)
value = (
tao()
if callable(tao)
else (tao if tao is not None else value)
)
item = getattr(value, "item", None)
value = item() if callable(item) else value
stake = float(value)
except (IndexError, KeyError, TypeError, ValueError):
continue
return stake if math.isfinite(stake) and stake >= 0 else None
return None
async def check_scheduler_ready(self) -> bool:
"""
Check if the video scheduler is ready to process synthetic requests.
Returns:
bool: True if scheduler is ready, False otherwise
"""
try:
async with httpx.AsyncClient() as client:
response = await client.get(self.scheduler_ready_endpoint, timeout=10)
response.raise_for_status()
data = response.json()
return data.get("ready", False)
except httpx.HTTPStatusError as e:
logger.error(f"HTTP error checking scheduler readiness: {e.response.status_code}")
return False
except httpx.RequestError as e:
logger.error(f"Request error checking scheduler readiness: {e}")
return False
except Exception as e:
logger.error(f"Unexpected error checking scheduler readiness: {e}")
return False
async def wait_for_scheduler_ready(self) -> None:
"""
Wait for the scheduler to be ready before proceeding with synthetic requests.
"""
logger.info("π Checking if video scheduler is ready...")
while not await self.check_scheduler_ready():
logger.info("β³ Waiting for scheduler server to be ready (all synthetic queues need to be populated)...")
await asyncio.sleep(10)
logger.info("β
Scheduler is ready! Proceeding with synthetic requests.")
async def download_video(self, video_url: str, verbose: bool = False) -> tuple[str, float]:
"""
Download a video from the given URL and save it to a temporary file.
Args:
video_url (str): The URL of the video to download.
verbose (bool): Whether to show download progress.
Returns:
tuple[str, float]: A tuple containing the path to the downloaded video file
and the time taken to download it.
Raises:
Exception: If the download fails or takes longer than the timeout.
"""
try:
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as vid_temp:
file_path = vid_temp.name # Path to the temporary file
if verbose:
logger.info(f"Downloading video from {video_url} to {file_path}")
timeout = aiohttp.ClientTimeout(sock_connect=30, total=300)
start_time = time.time() # Record start time
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get(video_url, allow_redirects=True) as response:
if response.status != 200:
raise Exception(f"Failed to download video. HTTP status: {response.status}")
with open(file_path, "wb") as f:
async for chunk in response.content.iter_chunked(2 * 1024 * 1024):
f.write(chunk)
end_time = time.time() # Record end time
download_time = end_time - start_time # Calculate download duration
if not os.path.exists(file_path) or os.path.getsize(file_path) == 0:
raise Exception(f"Download failed or file is empty: {file_path}")
if verbose:
logger.info(f"File successfully downloaded to: {file_path}")
logger.info(f"Download time: {download_time:.2f} seconds")
return file_path, download_time
except aiohttp.ServerTimeoutError:
raise Exception("Download failed: Server connection timed out")
except asyncio.TimeoutError:
raise Exception("Download timed out")
except aiohttp.ClientError as e:
raise Exception(f"Download failed due to a network error: {type(e).__name__}: {repr(e)}")
async def refresh_miner_manager(self, miner_uids: list[int]):
if not miner_uids:
return
miner_hotkeys = [self.metagraph.hotkeys[uid] for uid in miner_uids]
# Single query to fetch all miners
stmt = select(MinerMetadata).where(MinerMetadata.uid.in_(miner_uids))
result = self.miner_manager.session.execute(stmt)
miners = {miner.uid: miner for miner in result.scalars().all()}
delete_uids = []
for uid, latest_hotkey in zip(miner_uids, miner_hotkeys):
miner = miners.get(uid)
if miner is None:
continue
if miner.hotkey != latest_hotkey:
delete_uids.append(uid)
logger.info(
f"UID {uid} hotkey changed from {miner.hotkey} β {latest_hotkey}"
)
miner.hotkey = latest_hotkey # update record in-memory
if delete_uids:
delete_stmt = delete(MinerPerformanceHistory).where(
MinerPerformanceHistory.uid.in_(delete_uids)
)
self.miner_manager.session.execute(delete_stmt)
delete_stmt = delete(MinerMetadata).where(MinerMetadata.uid.in_(delete_uids))
self.miner_manager.session.execute(delete_stmt)
self.miner_manager.session.commit()
self.miner_manager.sync_miner_chain_metadata(miner_uids)
async def start_synthetic_epoch(self):
# Wait for scheduler to be ready first
await self.wait_for_scheduler_ready()
logger.info("β
β
β
β
β
Starting synthetic forward β
β
β
β
β
")
epoch_start_time = time.time()
miner_uids = self.filter_miners()
logger.debug(f"Initialized {len(miner_uids)} subnet neurons of total {len(self.metagraph.S)} neurons")
deduped_uid_reasons = self.synthetic_deduped_uid_reasons.copy()
deduped_uid_sources = self.synthetic_deduped_uid_sources.copy()
uids = self.miner_manager.consume(miner_uids)
logger.info(f"Filtered UIDs after consumption: {uids}")
random_uids = uids.copy()
random.shuffle(random_uids)
logger.info(f"Randomized UIDs: {random_uids}")
axons = [self.metagraph.axons[uid] for uid in random_uids]
logger.info(f"Sending TaskWarrantProtocol requests to {len(axons)} miners")
version = get_version()
task_warrant_synapse = TaskWarrantProtocol(version=version)
task_warrant_responses = await self.dendrite.forward(
axons=axons, synapse=task_warrant_synapse, timeout=60
)
logger.info(f"π Received {len(task_warrant_responses)} responses from miners for TaskWarrantProtocol requestsπ")
upscaling_miners = []
compression_miners = []
unknown_task_miners = []
for i, response in enumerate(task_warrant_responses):
uid = random_uids[i]
axon = axons[i]
if response.warrant_task == TaskType.UPSCALING:
upscaling_miners.append((axon, uid))
elif response.warrant_task == TaskType.COMPRESSION:
compression_miners.append((axon, uid))
else:
unknown_task_miners.append(uid)
if unknown_task_miners:
logger.info(f"π Checking database for {len(unknown_task_miners)} unknown task warrant miners")
db_task_types = self.miner_manager.get_miner_processing_task_types(unknown_task_miners)
resolved_from_db = []
defaulted_to_upscaling = []
for i, uid in enumerate(unknown_task_miners):
axon = axons[random_uids.index(uid)]
if uid in db_task_types:
db_task_type = db_task_types[uid]
if db_task_type == "upscaling":
upscaling_miners.append((axon, uid))
resolved_from_db.append(f"{uid}(upscaling)")
elif db_task_type == "compression":
compression_miners.append((axon, uid))
resolved_from_db.append(f"{uid}(compression)")
else:
upscaling_miners.append((axon, uid))
defaulted_to_upscaling.append(f"{uid}(unknown_db_value:{db_task_type})")
else:
upscaling_miners.append((axon, uid))
defaulted_to_upscaling.append(f"{uid}(no_db_record)")
upscaling_uids = [uid for _, uid in upscaling_miners]
compression_uids = [uid for _, uid in compression_miners]
all_uids = upscaling_uids + compression_uids
selected_task_types = {
**{uid: "upscaling" for uid in upscaling_uids},
**{uid: "compression" for uid in compression_uids},
}
await self.refresh_miner_manager(all_uids)
logger.info(f"π Grouped miners: {len(upscaling_miners)} upscaling, {len(compression_miners)} compression π")
if upscaling_uids:
logger.info(f"π Upscaling UIDs: {upscaling_uids}")
if compression_uids:
logger.info(f"π Compression UIDs: {compression_uids}")
if unknown_task_miners:
logger.info(f"β Unknown task UIDs processed: {unknown_task_miners}")
disable_synthetics = os.getenv("DISABLE_SYNTHETICS", "False").lower() == "true"
if disable_synthetics:
logger.info("Synthetic epoch disabled by DISABLE_SYNTHETICS env var, only ran TaskWarrant requests to gauge miner task types necessary to execute organics, sleeping for 30 minutes before refreshing")
await asyncio.sleep(1800)
return
await self.score_deduplicated_synthetic_miners(
deduped_uid_reasons,
deduped_uid_sources,
selected_task_types,
)
logger.info("Sleeping for 3 minutes before starting epoch")
await asyncio.sleep(180)
# ---- Run upscaling & compression epochs in parallel ---- #
async def _run_upscaling():
if not upscaling_miners:
return
logger.info("π§© Sleeping for 3 minutes before starting upscaling epoch")
await asyncio.sleep(180)
logger.info(f"Sending LengthCheckProtocol requests to {len(upscaling_miners)} upscaling miners")
upscaling_start_time = time.time()
upscaling_axons = [miner[0] for miner in upscaling_miners]
length_check_synapse = LengthCheckProtocol(version=version)
length_check_responses = await self.dendrite.forward(
axons=upscaling_axons, synapse=length_check_synapse, timeout=10
)
logger.info(f"π Received {len(length_check_responses)} responses from upscaling miners for LengthCheckProtocol requestsπ")
upscaling_content_lengths = []
for response in length_check_responses:
avail_max_len = response.max_content_length.value
if avail_max_len == 5:
upscaling_content_lengths.append(avail_max_len)
else:
upscaling_content_lengths.append(10)
logger.info(f"Upscaling content lengths: {upscaling_content_lengths}")
upscaling_miners_with_lengths = []
for i, (axon, uid) in enumerate(upscaling_miners):
content_length = upscaling_content_lengths[i] if i < len(upscaling_content_lengths) else 10
upscaling_miners_with_lengths.append((axon, uid, content_length))
logger.info(f"Sleeping for 3 minutes before querying upscaling miners")
await asyncio.sleep(180)
await self.process_upscaling_miners(upscaling_miners_with_lengths, version)
upscaling_processed_time = time.time() - upscaling_start_time
logger.info(f"Upscaling tasks processed in {upscaling_processed_time:.2f} seconds")
async def _run_compression():
if not compression_miners:
return
logger.info(f"Processing {len(compression_miners)} compression miners")
compression_start_time = time.time()
await self.process_compression_miners(compression_miners, version)
compression_processed_time = time.time() - compression_start_time
logger.info(f"Compression tasks processed in {compression_processed_time:.2f} seconds")
results = await asyncio.gather(
_run_upscaling(), _run_compression(), return_exceptions=True
)
for label, result in zip(["upscaling", "compression"], results):
if isinstance(result, BaseException):
logger.error(f"Parallel {label} epoch failed: {result}", exc_info=result)
epoch_processed_time = time.time() - epoch_start_time
logger.info(f"Completed one epoch within {epoch_processed_time:.2f} seconds")
logger.info(f"Sleeping for 1-2 hours before starting next cycle")
await asyncio.sleep(random.randint(3600 * 1, 3600 * 2))
# --------------------------------------------------------------------------- #
# Helper β turn the raw list of (axon, uid) into a dict {uid: (axon, uid)}
# --------------------------------------------------------------------------- #
def _miner_lookup(self, miners: List[Tuple[Any, int]]) -> dict[int, Tuple[Any, int]]:
"""{uid: (axon, uid)} β fast lookup while preserving the original tuple."""
return {uid: (axon, uid) for axon, uid in miners}
async def create_miner_batches(
self,
miners: List[Tuple[Any, int]],
batch_size: int,
task_type: str = "upscaling",
) -> List[List[Tuple[int, Tuple[Any, int]]]]:
"""
Build batches of miners for *task_type* (upscaling / compression).
Rules
-----
1. Miners with **fewest** performance-history rows go first.
2. Miners whose **most recent entry** is older than 2 h are eligible, subject to 70% probability of selection in batching.
3. Miners that already have >= CONFIG.score.max_performance_records rows
**and** whose latest entry is < 2 h are **skipped**.
"""
session = self.miner_manager.session
hours_threshold = datetime.utcnow() - timedelta(hours=CONFIG.score.synthetics_hours_threshold)
max_records = CONFIG.score.max_performance_records
info_new_uids = []
# ------------------------------------------------------------------- #
# 1. One-shot aggregated stats per UID (count + latest timestamp)
# ------------------------------------------------------------------- #
uid_stats_subq = (
session.query(
MinerPerformanceHistory.uid,
func.count(MinerPerformanceHistory.id).label("record_count"),
func.max(MinerPerformanceHistory.timestamp).label("latest_timestamp"),
)
.filter(
MinerPerformanceHistory.processed_task_type == task_type,
MinerPerformanceHistory.uid.in_([uid for _axon, uid in miners]),
)
.group_by(MinerPerformanceHistory.uid)
.subquery()
)
uid_stats = session.query(
uid_stats_subq.c.uid,
uid_stats_subq.c.record_count,
uid_stats_subq.c.latest_timestamp,
).all()
# uid β (record_count, latest_timestamp)
uid_info: dict[int, Tuple[int, datetime | None]] = {
row.uid: (row.record_count or 0, row.latest_timestamp) for row in uid_stats
}
# ------------------------------------------------------------------- #
# 2. Miners that have *zero* rows are the highest priority
# ------------------------------------------------------------------- #
all_uids = {uid for _axon, uid in miners}
for uid in all_uids - uid_info.keys():
uid_info[uid] = (0, None)
# ------------------------------------------------------------------- #
# 3. Build a fast lookup {uid: original_tuple}
# ------------------------------------------------------------------- #
miner_by_uid = self._miner_lookup(miners)
# ------------------------------------------------------------------- #
# 4. Filter + priority key
# ------------------------------------------------------------------- #
eligible: List[Tuple[Tuple[int, datetime], Tuple[Any, int]]] = []
for uid in all_uids:
miner_tuple = miner_by_uid[uid]
rec_cnt, latest_ts = uid_info[uid]
# ---- Rule 3: skip capped miners with recent performance record ----
if rec_cnt >= max_records and latest_ts and latest_ts >= hours_threshold:
logger.info(
f"Skipping miner uid={uid}: {rec_cnt} records, last update {latest_ts}"
)
continue
# ---- Rule 2: include if never seen, below capacity or stale ----
if rec_cnt < max_records or not latest_ts \
or (latest_ts < hours_threshold and random.random() < CONFIG.score.synthetics_select_probability):
priority = (
rec_cnt, # fewer records first
latest_ts if latest_ts else datetime.min, # oldest first
)
if rec_cnt == 0:
info_new_uids.append(uid)
eligible.append((priority, miner_tuple))
# ------------------------------------------------------------------- #
# 5. Sort & batch
# ------------------------------------------------------------------- #
eligible.sort(key=lambda x: x[0]) # by priority tuple
sorted_miners = [(prio[0], miner) for prio, miner in eligible]
batches = [
sorted_miners[i : i + batch_size]
for i in range(0, len(sorted_miners), batch_size)
]
logger.info(
f"Created {len(batches)} {task_type} batches (sizeβ€{batch_size}). "
f"Selected {len(sorted_miners)}/{len(miners)} miners."
f" New UIDs with no history: {info_new_uids}"
)
if eligible:
top_uid = eligible[0][1][1] # (axon, uid) β uid
logger.info(
f"Top-priority miner uid={top_uid} β records={uid_info[top_uid][0]}"
)
return batches
async def call_miner_batch(self, axons, synapse, batch, timeout=60):
start = time.perf_counter()
try:
raw = await self.dendrite.forward(
axons=axons,
synapse=synapse,
timeout=timeout,
)
duration = (time.perf_counter() - start) * 1000 # ms
logger.info(f"π Received {len(raw)} responses from miners in {duration} msπ")
return raw
except Exception as e:
logger.error(f"Unexpected error calling miner batch: {e}", exc_info=True)
return []
async def call_miner(self, axon, synapse, uid, timeout=60):
start = time.perf_counter()
try:
raw = await self.dendrite.forward(
axons=[axon],
synapse=synapse,
timeout=timeout,
)
duration = (time.perf_counter() - start) * 1000 # ms
try:
result = raw[0]
except Exception as e:
logger.error(
f"UID {uid} β invalid response structure after {duration:.2f} ms | {e}",
exc_info=True
)
return {
"uid": uid,
"result": None,
"error": e,
"latency_ms": duration,
}
logger.info(f"UID {uid} β success | {duration:.2f} ms")
return {
"uid": uid,
"result": result,
"error": None,
"latency_ms": duration,
}
except Exception as e:
duration = (time.perf_counter() - start) * 1000 # ms
logger.error(
f"UID {uid} β failure after {duration:.2f} ms | {type(e).__name__}: {e}",
exc_info=True
)
return {
"uid": uid,
"result": None, # EXACT same shape as original gather usage
"error": e,
"latency_ms": duration,
}
def _response_video_urls(self, response, expected_count: int) -> list[str]:
miner_response = getattr(response, "miner_response", None)
if miner_response is None:
return [""] * expected_count
urls = list(getattr(miner_response, "optimized_video_urls", []) or [])
legacy_url = getattr(miner_response, "optimized_video_url", "")
if not urls and legacy_url:
urls = [legacy_url]
if len(urls) < expected_count:
urls.extend([""] * (expected_count - len(urls)))
return urls[:expected_count]
def _synthetic_response_url_key(self, url: str) -> str:
return (url or "").strip()
def _duplicate_synthetic_response_url_reasons(
self,
uids: list[int],
distorted_urls: list[str],
query_indices: list[int],
task_type: str,
) -> dict[int, str]:
grouped_indices: dict[tuple[int, str], list[int]] = {}
for idx, (url, query_idx) in enumerate(zip(distorted_urls, query_indices)):
url_key = self._synthetic_response_url_key(url)
if not url_key or len(url_key) < 10:
continue
grouped_indices.setdefault((query_idx, url_key), []).append(idx)
duplicate_reasons: dict[int, str] = {}
for (query_idx, url), indices in grouped_indices.items():
if len(indices) <= 1:
continue
duplicate_uids = [uids[idx] for idx in indices]
logger.warning(
f"Zeroing all synthetic {task_type} responses with duplicate URL "
f"{url} for query {query_idx}: uids={duplicate_uids}"
)
for duplicate_idx in indices:
reason = (
f"MINER FAILURE: duplicate synthetic {task_type} response URL "
f"for query {query_idx}: {url} shared by UIDs {duplicate_uids}"
)
duplicate_reasons[duplicate_idx] = reason
if duplicate_reasons:
logger.info(
f"Zeroed {len(duplicate_reasons)} duplicate synthetic {task_type} "
f"response URLs before scoring"
)
return duplicate_reasons
async def call_miner_polling(
self,
axon,
synapse_job,
uid: int,
PollProtocolClass,
poll_interval: float = 60.0,
max_polls: int = 20,
):
"""Polling-based miner call for organic requests.
Phase 1: Sends the job kick-off synapse and receives a ``job_id``
immediately (30s timeout β just long enough for a network round-trip).
Phase 2: Polls at ``poll_interval`` second intervals until the miner
reports ``completed`` or ``failed``, or ``max_polls`` is exhausted
(default: 20 * 60s = 20-minute budget).
Args:
axon: Target miner axon.
synapse_job: A ``VideoCompressionJobProtocol`` or
``VideoUpscalingJobProtocol`` instance with the task payload.
uid: Miner UID (used for logging).
PollProtocolClass: ``VideoCompressionPollProtocol`` or
``VideoUpscalingPollProtocol``.
poll_interval: Seconds between polls (default 20).
max_polls: Maximum poll attempts (default 60 β 20-min budget).
Returns:
Dict with keys ``uid``, ``result`` (synapse with populated
``miner_response.optimized_video_url``), ``error``, ``latency_ms``.
"""
start = time.perf_counter()
def _empty(error_msg):
return {
"uid": uid,
"result": synapse_job,
"error": error_msg,
"latency_ms": (time.perf_counter() - start) * 1000,
}
# ---- Phase 1: kick-off ----
# The validator owns the job_id β assign it before sending.
job_id = str(uuid.uuid4())
synapse_job.job_id = job_id
logger.info(f"UID {uid} β sending job kick-off | job_id={job_id} ")
try:
raw = await self.dendrite.forward(
axons=[axon], synapse=synapse_job, timeout=60
)
accepted = raw[0].job_response.accepted
except Exception as e:
logger.error(f"UID {uid} β polling kick-off failed: {e}")
return _empty(str(e))
if not accepted:
logger.warning(
f"UID {uid} β miner did not accept the job (job_id={job_id!r})"
)
return _empty("not accepted")
logger.info(f"UID {uid} β job kick-off accepted | job_id={job_id}")
# ---- Phase 2: poll loop ----
for poll_num in range(1, max_polls + 1):
await asyncio.sleep(poll_interval)
try:
poll_syn = PollProtocolClass(job_id=job_id)
raw = await self.dendrite.forward(
axons=[axon], synapse=poll_syn, timeout=15
)
resp = raw[0].poll_response
except Exception as e:
logger.warning(f"UID {uid} | poll #{poll_num} error: {e}")
continue
logger.info(f"UID {uid} | poll #{poll_num} β status={resp.status}")
if resp.status == "completed":
# Shim result so all downstream code can access
# .miner_response.optimized_video_url unchanged.
response_urls = list(getattr(resp, "optimized_video_urls", []) or [])
legacy_url = getattr(resp, "optimized_video_url", "")
if not response_urls and legacy_url:
response_urls = [legacy_url]
synapse_job.miner_response = MinerResponse(
optimized_video_urls=response_urls
)
return {
"uid": uid,
"result": synapse_job,
"error": None,
"latency_ms": (time.perf_counter() - start) * 1000,
}
elif resp.status == "failed":
logger.error(f"UID {uid} β job {job_id} reported failed")
return _empty("miner reported failed")
# status == "processing" β keep polling
logger.error(
f"UID {uid} β polling timed out after {max_polls} attempts for job {job_id}"
)
return _empty("polling timeout")
async def process_upscaling_miners(self, upscaling_miners_with_lengths, version):
"""Process all upscaling miners concurrently with the same bundled challenge."""
upscaling_miners = [(axon, uid) for axon, uid, _ in upscaling_miners_with_lengths]
upscaling_content_lengths = {uid: length for _, uid, length in upscaling_miners_with_lengths}
num_miners = len(upscaling_miners)
if num_miners == 0:
return
miner_scores = {uid: miner.accumulate_score for uid, miner in self.miner_manager.query([uid for _, uid in upscaling_miners]).items()}
upscaling_miners.sort(key=lambda miner: miner_scores.get(miner[1], float("-inf")), reverse=True)
query_count = SYNTHETIC_QUERIES_PER_MINER
shared_content_length = min(upscaling_content_lengths.values()) if upscaling_content_lengths else 5
content_lengths = [shared_content_length] * query_count
uids = [uid for _, uid in upscaling_miners]
axons = [axon for axon, _ in upscaling_miners]
logger.info(
f"π§© Processing {num_miners} upscaling miners concurrently with "
f"{query_count} shared synthetic queries π§©"
)
batch_start_time = time.time()
round_id = str(uuid.uuid4())
payload_urls, video_ids, uploaded_object_names, synapses, task_types = await self.challenge_synthesizer.build_synthetic_protocol(
content_lengths, version, round_id, bundle_protocols=True
)
query_count = len(payload_urls)
logger.info(f"Built upscaling challenge protocol: payload URLs: {payload_urls}\nvideo IDs: {video_ids}")
timestamp = datetime.now(timezone.utc).isoformat()
responses = await self.call_miner_batch(
axons,
synapses[0],
num_miners,
timeout=135
)
logger.info(f"π² Received {len(responses)} upscaling responses from miners π²")
reference_video_paths = []
for video_id in video_ids:
reference_video_path = get_trim_video_path(video_id)
if not os.path.exists(reference_video_path):
logger.warning(f"β οΈ Reference video file missing for video_id {video_id}: {reference_video_path}")
reference_video_paths.append(reference_video_path)
flat_uids = []
flat_distorted_urls = []
flat_payload_urls = []
flat_reference_paths = []
flat_video_ids = []
flat_uploaded_object_names = []
flat_content_lengths = []
flat_task_types = []
flat_query_indices = []
for response_idx, uid in enumerate(uids):
response = responses[response_idx] if response_idx < len(responses) else None
response_urls = self._response_video_urls(response, query_count)
for query_idx, distorted_url in enumerate(response_urls):
flat_uids.append(uid)
flat_distorted_urls.append(distorted_url)
flat_payload_urls.append(payload_urls[query_idx])
flat_reference_paths.append(reference_video_paths[query_idx])
flat_video_ids.append(video_ids[query_idx])
flat_uploaded_object_names.append(uploaded_object_names[query_idx])
flat_content_lengths.append(content_lengths[query_idx])
flat_task_types.append(task_types[query_idx])
flat_query_indices.append(query_idx)
duplicate_url_reasons = self._duplicate_synthetic_response_url_reasons(
flat_uids,
flat_distorted_urls,
flat_query_indices,
"upscaling",
)
total_scoring_responses = len(flat_uids)
scoring_batch_size = UPSCALING_SCORING_BATCH_SIZE
scoring_batch_count = (total_scoring_responses + scoring_batch_size - 1) // scoring_batch_size
logger.info(
f"Scoring {total_scoring_responses} upscaling query responses from "
f"{num_miners} miners in {scoring_batch_count} batches of up to {scoring_batch_size}"
)
deferred_scoring_results = []
for batch_idx, batch_start in enumerate(range(0, total_scoring_responses, scoring_batch_size), start=1):
batch_end = min(batch_start + scoring_batch_size, total_scoring_responses)
batch_uids = flat_uids[batch_start:batch_end]
batch_timer = time.time()
logger.info(
f"Scoring upscaling batch {batch_idx}/{scoring_batch_count}: "
f"responses {batch_start + 1}-{batch_end}/{total_scoring_responses}, "
f"uids={batch_uids}"
)
batch_duplicate_url_reasons = {
idx - batch_start: reason
for idx, reason in duplicate_url_reasons.items()
if batch_start <= idx < batch_end
}
scoring_result = await self.score_upscalings(
batch_uids,
[],
flat_payload_urls[batch_start:batch_end],
flat_reference_paths[batch_start:batch_end],
timestamp,
flat_video_ids[batch_start:batch_end],
flat_uploaded_object_names[batch_start:batch_end],
flat_content_lengths[batch_start:batch_end],
flat_task_types[batch_start:batch_end],
round_id,
distorted_urls=flat_distorted_urls[batch_start:batch_end],
duplicate_url_reasons=batch_duplicate_url_reasons,
commit_scores=False,
)
deferred_scoring_results.append(scoring_result)
logger.info(
f"Completed upscaling scoring batch {batch_idx}/{scoring_batch_count} "
f"in {time.time() - batch_timer:.2f} seconds"
)
self._commit_upscaling_scores(deferred_scoring_results)
# These collections do not necessarily have the same length, so clean
# each kind of resource independently.
for ref_path in reference_video_paths:
if ref_path and os.path.exists(ref_path):
try:
os.unlink(ref_path)
except Exception as e:
logger.error(f"Error deleting reference video file {ref_path}: {e}")
for payload_path in payload_urls:
if payload_path and os.path.exists(payload_path):
try:
os.unlink(payload_path)
except Exception as e:
logger.error(f"Error deleting payload video file {payload_path}: {e}")
for uploaded_object_name in uploaded_object_names:
try:
await storage_client.delete_file(uploaded_object_name)
except Exception as e:
logger.error(f"Error deleting uploaded object {uploaded_object_name}: {e}")
batch_processed_time = time.time() - batch_start_time
logger.info(f"Completed upscaling batch within {batch_processed_time:.2f} seconds")
logger.info(f"Scored {total_scoring_responses} upscaling query responses from {num_miners} miners")
async def process_compression_miners(self, compression_miners, version):
"""Process all compression miners concurrently with the same bundled challenge."""
num_miners = len(compression_miners)
if num_miners == 0:
return
miner_scores = {uid: miner.accumulate_score for uid, miner in self.miner_manager.query([uid for _, uid in compression_miners]).items()}
compression_miners = sorted(compression_miners, key=lambda miner: miner_scores.get(miner[1], float("-inf")), reverse=True)
query_count = SYNTHETIC_QUERIES_PER_MINER
logger.info(
f"π§© Processing {num_miners} compression miners concurrently with "
f"{query_count} shared synthetic queries π§©"
)
round_id = str(uuid.uuid4())
uids = []
axons = []
for axon, uid in compression_miners:
uids.append(uid)
axons.append(axon)
vmaf_threshold = random.choice(list(VMAF_QUALITY_THRESHOLD))
vmaf_thresholds = [vmaf_threshold] * query_count
target_codec = random.choice(TARGET_CODECS)
codec_mode = random.choice(CODEC_MODES)
target_bitrate = random.choice(TARGET_BITRATES)
payload_urls, video_ids, uploaded_object_names, synapses = await self.challenge_synthesizer.build_compression_protocol(
vmaf_thresholds,
query_count,
version,
round_id,
target_codec,
codec_mode,
target_bitrate,
bundle_protocols=True,
)
query_count = len(payload_urls)
logger.warning(
f"Built compression challenge protocol for {num_miners} miners, "
f"{query_count} queries, VMAF threshold {vmaf_thresholds[0]}, codec {target_codec}, "
f"mode {codec_mode}, bitrate {target_bitrate} Mbps"
)
timestamp = datetime.now(timezone.utc).isoformat()
logger.debug(f"Processing compression UIDs: {uids}")
batch_start_time = time.time()
responses = await self.call_miner_batch(
axons,
synapses[0],
num_miners,
timeout=180,
)
logger.info(f"π² Received {len(responses)} compression responses from miners π²")
reference_video_paths = []
for video_id in video_ids:
reference_video_path = get_perumted_video_path(video_id)
if not os.path.exists(reference_video_path):
logger.warning(f"β οΈ Reference video file missing for video_id {video_id}: {reference_video_path}")
reference_video_paths.append(reference_video_path)
flat_uids = []
flat_distorted_urls = []
flat_payload_urls = []
flat_reference_paths = []
flat_video_ids = []
flat_uploaded_object_names = []
flat_vmaf_thresholds = []
flat_query_indices = []
for response_idx, uid in enumerate(uids):
response = responses[response_idx] if response_idx < len(responses) else None
response_urls = self._response_video_urls(response, query_count)
for query_idx, distorted_url in enumerate(response_urls):
flat_uids.append(uid)
flat_distorted_urls.append(distorted_url)
flat_payload_urls.append(payload_urls[query_idx])
flat_reference_paths.append(reference_video_paths[query_idx])
flat_video_ids.append(video_ids[query_idx])
flat_uploaded_object_names.append(uploaded_object_names[query_idx])
flat_vmaf_thresholds.append(getattr(vmaf_thresholds[query_idx], "value", vmaf_thresholds[query_idx]))
flat_query_indices.append(query_idx)
duplicate_url_reasons = self._duplicate_synthetic_response_url_reasons(
flat_uids,
flat_distorted_urls,
flat_query_indices,
"compression",
)
# Concurrently start all downloads that have valid URLs,
# limited by a semaphore to prevent timeouts on large fleets
semaphore = asyncio.Semaphore(15)
async def _download_with_semaphore(uid_val, url_str):
logger.info(f"UID {uid_val}: Queuing download for distorted video")
async with semaphore:
try:
logger.info(f"UID {uid_val}: Starting download for distorted video")
return await self.download_video(url_str)
except Exception as e:
return e
download_tasks = []
for idx, (uid_val, url) in enumerate(zip(flat_uids, flat_distorted_urls)):
if idx in duplicate_url_reasons:
logger.warning(
f"UID {uid_val}: skipping distorted video download because "
f"response URL was deduplicated before compression scoring"
)
download_tasks.append(asyncio.create_task(asyncio.sleep(0, result=None)))
elif not url or len(url) < 10:
logger.error(f"UID {uid_val}: invalid or missing distorted video download URL: {url}")
# Create a task that simply returns None
download_tasks.append(asyncio.create_task(asyncio.sleep(0, result=None)))
else:
download_tasks.append(
asyncio.create_task(_download_with_semaphore(uid_val, url))
)
# Wait for all downloads to finish
download_results = await asyncio.gather(*download_tasks, return_exceptions=True)
# Process the results, handling any exceptions
distorted_file_paths = []
for uid_val, url, result in zip(flat_uids, flat_distorted_urls, download_results):
if isinstance(result, Exception):
logger.error(f"UID {uid_val}: Failed to download distorted video from {url} - {str(result)}")
distorted_file_paths.append(None)
elif result is None:
# Already logged in the loop above
distorted_file_paths.append(None)
elif isinstance(result, tuple) and len(result) >= 1:
distorted_file_paths.append(result[0])
else:
logger.error(f"UID {uid_val}: Unexpected result from download_video for {url} - {result}")
distorted_file_paths.append(None)
batch_processed_time = time.time() - batch_start_time
logger.info(f"Completed compression gathering and downloading within {batch_processed_time:.2f} seconds")
total_scoring_responses = len(flat_uids)
scoring_batch_size = COMPRESSION_SCORING_BATCH_SIZE
scoring_batch_count = (total_scoring_responses + scoring_batch_size - 1) // scoring_batch_size
logger.info(
f"Scoring {total_scoring_responses} compression query responses from "
f"{num_miners} miners in {scoring_batch_count} batches of up to {scoring_batch_size}"
)
compression_score_cache: CompressionScoreCache = {}
deferred_scoring_results = []
for batch_idx, batch_start in enumerate(range(0, total_scoring_responses, scoring_batch_size), start=1):
batch_end = min(batch_start + scoring_batch_size, total_scoring_responses)
batch_uids = flat_uids[batch_start:batch_end]
batch_timer = time.time()
logger.info(
f"Scoring compression batch {batch_idx}/{scoring_batch_count}: "
f"responses {batch_start + 1}-{batch_end}/{total_scoring_responses}, "
f"uids={batch_uids}"
)
batch_duplicate_url_reasons = {
idx - batch_start: reason
for idx, reason in duplicate_url_reasons.items()
if batch_start <= idx < batch_end
}
scoring_result = await self.score_compressions(
batch_uids,
[],
distorted_file_paths[batch_start:batch_end],
flat_payload_urls[batch_start:batch_end],
flat_reference_paths[batch_start:batch_end],
timestamp,
flat_video_ids[batch_start:batch_end],
flat_uploaded_object_names[batch_start:batch_end],
flat_vmaf_thresholds[batch_start:batch_end],
target_codec,
codec_mode,
target_bitrate,
round_id,
distorted_urls=flat_distorted_urls[batch_start:batch_end],
duplicate_url_reasons=batch_duplicate_url_reasons,
compression_score_cache=compression_score_cache,
commit_scores=False,
)
deferred_scoring_results.append(scoring_result)
logger.info(
f"Completed compression scoring batch {batch_idx}/{scoring_batch_count} "
f"in {time.time() - batch_timer:.2f} seconds"
)
self._commit_compression_scores(deferred_scoring_results)
# There is one distorted file per miner response, but only one reference
# and uploaded object per query. Zipping these lists would stop after the
# query count and leak the remaining distorted files.
for dist_path in distorted_file_paths:
if dist_path and os.path.exists(dist_path):
try:
os.unlink(dist_path)
except Exception as e:
logger.error(f"Error deleting distorted video file {dist_path}: {e}")
for ref_path in reference_video_paths:
if ref_path and os.path.exists(ref_path):
try:
os.unlink(ref_path)
except Exception as e:
logger.error(f"Error deleting reference video file {ref_path}: {e}")
for payload_path in payload_urls:
if payload_path and os.path.exists(payload_path):
try:
os.unlink(payload_path)
except Exception as e:
logger.error(f"Error deleting payload video file {payload_path}: {e}")
for uploaded_object_name in uploaded_object_names:
try:
await storage_client.delete_file(uploaded_object_name)
except Exception as e:
logger.error(f"Error deleting uploaded object {uploaded_object_name}: {e}")
async def start_organic_loop(self):
"""Start organic processing loop for both upscaling and compression tasks asynchronously."""
try:
# Create tasks for both upscaling and compression processing
upscaling_task = asyncio.create_task(self._process_organic_upscaling_loop())
compression_task = asyncio.create_task(self._process_organic_compression_loop())
# Wait for both tasks to complete (they run indefinitely)
await asyncio.gather(upscaling_task, compression_task)
except Exception as e:
logger.error(f"Error during organic processing loop: {e}")
async def _process_organic_upscaling_loop(self):
"""Process organic upscaling tasks in a loop."""
while True:
try:
await self.should_process_organic_upscaling()
await asyncio.sleep(5)
except Exception as e:
logger.error(f"Error during organic upscaling processing: {e}")
await asyncio.sleep(5)
async def _process_organic_compression_loop(self):
"""Process organic compression tasks in a loop."""
while True:
try:
await self.should_process_organic_compression()
await asyncio.sleep(5)
except Exception as e:
logger.error(f"Error during organic compression processing: {e}")
await asyncio.sleep(5)
async def score_upscalings(
self,
uids: list[int],
responses: list[protocol.Synapse],
payload_urls: list[str],
reference_video_paths: list[str],
timestamp: str,
video_ids: list[str],
uploaded_object_names: list[str],
content_lengths: list[int],
task_types: list[str],
round_id: str,
distorted_urls: list[str] | None = None,
duplicate_url_reasons: dict[int, str] | None = None,
commit_scores: bool = True,
):
if distorted_urls is None:
distorted_urls = []
for uid, response in zip(uids, responses):
distorted_urls.append(response.miner_response.optimized_video_url)
logger.info(f"payloads: {payload_urls}\nresponses: {distorted_urls}")
duplicate_url_reasons = duplicate_url_reasons or {}
scoring_indices = [
idx for idx in range(len(uids)) if idx not in duplicate_url_reasons
]
if duplicate_url_reasons:
logger.info(
f"Sending {len(scoring_indices)}/{len(uids)} upscaling responses "
f"to scorer after exact URL deduplication"
)
if scoring_indices:
score_response = await self.score_client_upscaling.post(
"/score_upscaling_synthetics",
json = {
"uids": [uids[idx] for idx in scoring_indices],
"payload_urls": [payload_urls[idx] for idx in scoring_indices],
"distorted_urls": [distorted_urls[idx] for idx in scoring_indices],
"reference_paths": [reference_video_paths[idx] for idx in scoring_indices],
"video_ids": [video_ids[idx] for idx in scoring_indices],
"uploaded_object_names": [uploaded_object_names[idx] for idx in scoring_indices],
"content_lengths": [content_lengths[idx] for idx in scoring_indices],
"task_types": [task_types[idx] for idx in scoring_indices]
},
timeout=600
)
response_data = score_response.json()
else:
response_data = {}
scored_quality_scores = response_data.get("quality_scores", [])
scored_length_scores = response_data.get("length_scores", [])
scored_final_scores = response_data.get("final_scores", [])
scored_vmaf_scores = response_data.get("vmaf_scores", [])
scored_pieapp_scores = response_data.get("pieapp_scores", [])
scored_reasons = response_data.get("reasons", [])
def merge_scored_values(scored_values, duplicate_default, missing_default):
merged_values = []
scored_pos = 0
for idx in range(len(uids)):
if idx in duplicate_url_reasons:
merged_values.append(duplicate_default(idx))
continue
if scored_pos < len(scored_values):
merged_values.append(scored_values[scored_pos])
else:
merged_values.append(missing_default)
scored_pos += 1
return merged_values
quality_scores = merge_scored_values(scored_quality_scores, lambda _idx: 0.0, 0.0)
length_scores = merge_scored_values(scored_length_scores, lambda _idx: 0.0, 0.0)
final_scores = merge_scored_values(scored_final_scores, lambda _idx: 0.0, 0.0)
vmaf_scores = merge_scored_values(scored_vmaf_scores, lambda _idx: 0.0, 0.0)
pieapp_scores = merge_scored_values(scored_pieapp_scores, lambda _idx: 0.0, 0.0)
reasons = merge_scored_values(
scored_reasons,
lambda idx: duplicate_url_reasons[idx],
"No reason provided",
)
scoring_result = {
"round_id": round_id,
"uids": uids,
"vmaf_scores": vmaf_scores,
"pieapp_scores": pieapp_scores,
"quality_scores": quality_scores,
"length_scores": length_scores,
"final_scores": final_scores,
"reasons": reasons,
"content_lengths": content_lengths,
"payload_urls": payload_urls,
"distorted_urls": distorted_urls,
"timestamp": timestamp,
}
if commit_scores:
self._commit_upscaling_scores([scoring_result])
return scoring_result
def _commit_upscaling_scores(self, scoring_results):
if not scoring_results:
return
round_id = scoring_results[0]["round_id"]
if any(result["round_id"] != round_id for result in scoring_results):
raise ValueError("Cannot commit upscaling scores from different rounds")
def combine(key):
return [
value
for result in scoring_results
for value in result[key]
]
uids = combine("uids")
vmaf_scores = combine("vmaf_scores")
pieapp_scores = combine("pieapp_scores")
quality_scores = combine("quality_scores")
length_scores = combine("length_scores")
final_scores = combine("final_scores")
reasons = combine("reasons")
content_lengths = combine("content_lengths")
payload_urls = combine("payload_urls")
distorted_urls = combine("distorted_urls")
timestamp = scoring_results[0]["timestamp"]
logger.info(f"Updating miner manager with {len(quality_scores)} upscaling scores after synthetic requests processing")
miner_hotkeys = [self.metagraph.hotkeys[uid] for uid in uids]
accumulate_scores, applied_multipliers = self.miner_manager.step_synthetics_upscaling(
round_id, uids, miner_hotkeys, vmaf_scores, pieapp_scores, quality_scores, length_scores, final_scores, content_lengths
)
max_length = max(
len(uids),
len(quality_scores),
len(length_scores),
len(final_scores),
len(vmaf_scores),
len(pieapp_scores),
len(reasons),
len(content_lengths),
len(applied_multipliers),
len(accumulate_scores),
)
vmaf_scores.extend([0.0] * (max_length - len(vmaf_scores)))
pieapp_scores.extend([0.0] * (max_length - len(pieapp_scores)))
quality_scores.extend([0.0] * (max_length - len(quality_scores)))
length_scores.extend([0.0] * (max_length - len(length_scores)))
final_scores.extend([0.0] * (max_length - len(final_scores)))
reasons.extend(["No reason provided"] * (max_length - len(reasons)))
content_lengths.extend([0.0] * (max_length - len(content_lengths)))
applied_multipliers.extend([0.0] * (max_length - len(applied_multipliers)))
logger.info(f"Synthetic upscaling scoring results for {len(uids)} query responses")
logger.info(f"Uids: {uids}")
for uid, vmaf_score, pieapp_score, quality_score, length_score, final_score, reason, content_length, applied_multiplier in zip(
uids, vmaf_scores, pieapp_scores, quality_scores, length_scores, final_scores, reasons, content_lengths, applied_multipliers
):
logger.info(
f"{uid} ** VMAF: {vmaf_score:.2f} ** PieAPP: {pieapp_score:.2f} ** Quality: {quality_score:.4f} "
f"** Length: {length_score:.4f} ** Content Length: {content_length} ** Applied_multiplier {applied_multiplier} ** Final: {final_score:.4f} || {reason}"
)
miner_data = {
"validator_uid": self.my_subnet_uid,
"validator_hotkey": self.wallet.hotkey.ss58_address,
"request_type": "Synthetic",
"processing_task_type": "upscaling",
"miner_uids": uids,
"miner_hotkeys": miner_hotkeys,
"vmaf_scores": vmaf_scores,
"pieapp_scores": pieapp_scores,
"quality_scores": quality_scores,
"length_scores": length_scores,
"final_scores": final_scores,
"accumulate_scores": accumulate_scores,
"applied_multipliers": applied_multipliers,
"status": reasons,
"task_urls": payload_urls,
"processed_urls": distorted_urls,
"timestamp": timestamp
}
success = send_upscaling_data_to_dashboard(miner_data)
if success:
logger.info("Data successfully sent to dashboard")
else:
logger.info("Failed to send data to dashboard")
async def score_compressions(
self,
uids: list[int],
responses: list[protocol.Synapse],
distorted_file_paths: list[str],
payload_urls: list[str],
reference_video_paths: list[str],
timestamp: str,
video_ids: list[str],
uploaded_object_names: list[str],
vmaf_thresholds: List[float],
target_codec: str,
codec_mode: str,
target_bitrate: float,
round_id: str,
distorted_urls: list[str] | None = None,
duplicate_url_reasons: dict[int, str] | None = None,
compression_score_cache: CompressionScoreCache | None = None,
commit_scores: bool = True,
):
if distorted_urls is None:
distorted_urls = []
for uid, response in zip(uids, responses):
distorted_urls.append(response.miner_response.optimized_video_url)
logger.info(f"payload: {payload_urls[:SYNTHETIC_QUERIES_PER_MINER]}\nresponses: {distorted_urls}")
duplicate_url_reasons = duplicate_url_reasons or {}
scoring_indices = [
idx for idx in range(len(uids)) if idx not in duplicate_url_reasons
]
if duplicate_url_reasons:
logger.info(
f"Sending {len(scoring_indices)}/{len(uids)} compression responses "
f"to scorer after exact URL deduplication"
)
if scoring_indices:
score_response = await self.score_client_compression.post(
"/score_compression_synthetics",
json = {
"uids": [uids[idx] for idx in scoring_indices],
"distorted_file_paths": [distorted_file_paths[idx] for idx in scoring_indices],
"reference_paths": [reference_video_paths[idx] for idx in scoring_indices],
"video_ids": [video_ids[idx] for idx in scoring_indices],
"uploaded_object_names": [uploaded_object_names[idx] for idx in scoring_indices],
"vmaf_thresholds": [vmaf_thresholds[idx] for idx in scoring_indices],
"distorted_urls": [distorted_urls[idx] for idx in scoring_indices],
"target_codec": target_codec,
"codec_mode": codec_mode,
"target_bitrate": target_bitrate
},
timeout=600
)
response_data = score_response.json()
else:
response_data = {}
scored_compression_rates = response_data.get("compression_rates", [])
scored_final_scores = response_data.get("final_scores", [])
scored_vmaf_scores = response_data.get("vmaf_scores", [])
scored_base_vmaf_scores = response_data.get("base_vmaf_scores") or []
scored_reasons = response_data.get("reasons", [])
def merge_scored_values(scored_values, duplicate_default, missing_default):
merged_values = []
scored_pos = 0
for idx in range(len(uids)):
if idx in duplicate_url_reasons:
merged_values.append(duplicate_default(idx))
continue
if scored_pos < len(scored_values):
merged_values.append(scored_values[scored_pos])
else:
merged_values.append(missing_default)
scored_pos += 1
return merged_values
compression_rates = merge_scored_values(
scored_compression_rates, lambda _idx: 0.9999, 0.5
)
final_scores = merge_scored_values(scored_final_scores, lambda _idx: 0.0, 0.0)
vmaf_scores = merge_scored_values(scored_vmaf_scores, lambda _idx: 0.0, 0.0)
base_vmaf_scores = merge_scored_values(scored_base_vmaf_scores, lambda _idx: None, None)
reasons = merge_scored_values(
scored_reasons,
lambda idx: duplicate_url_reasons[idx],
"No reason provided",
)
if compression_score_cache is None:
compression_score_cache = {}
duplicate_score_owners = find_duplicate_compression_scores(
uids,
video_ids,
vmaf_scores,
base_vmaf_scores,
vmaf_thresholds,
compression_rates,
final_scores,
compression_score_cache,
)
for idx, first_uid in duplicate_score_owners.items():
duplicate_reason = (
"MINER FAILURE: duplicate synthetic compression score metrics "
f"for input {video_ids[idx]}; matches earlier UID {first_uid}"
)
logger.warning(
f"UID {uids[idx]}: {duplicate_reason}. Assigning score of 0."
)
final_scores[idx] = 0.0
reasons[idx] = f"{duplicate_reason}; original scorer result: {reasons[idx]}"
if duplicate_score_owners:
logger.info(
f"Zeroed {len(duplicate_score_owners)} duplicate synthetic "
"compression results based on normalized primary scoring metrics"
)
scoring_result = {
"round_id": round_id,
"uids": uids,
"vmaf_scores": vmaf_scores,
"base_vmaf_scores": base_vmaf_scores,
"final_scores": final_scores,
"reasons": reasons,
"compression_rates": compression_rates,
"vmaf_thresholds": vmaf_thresholds,
"payload_urls": payload_urls,
"distorted_urls": distorted_urls,
"timestamp": timestamp,
}
if commit_scores:
self._commit_compression_scores([scoring_result])
return scoring_result
def _commit_compression_scores(self, scoring_results):
if not scoring_results:
return
round_id = scoring_results[0]["round_id"]
if any(result["round_id"] != round_id for result in scoring_results):
raise ValueError("Cannot commit compression scores from different rounds")
def combine(key):
return [
value
for result in scoring_results
for value in result[key]
]
uids = combine("uids")
vmaf_scores = combine("vmaf_scores")
base_vmaf_scores = combine("base_vmaf_scores")
final_scores = combine("final_scores")
reasons = combine("reasons")
compression_rates = combine("compression_rates")
vmaf_thresholds = combine("vmaf_thresholds")
payload_urls = combine("payload_urls")
distorted_urls = combine("distorted_urls")
timestamp = scoring_results[0]["timestamp"]
logger.info(f"Updating miner manager with {len(compression_rates)} compression miner scores after synthetic requests processing")
miner_hotkeys = [self.metagraph.hotkeys[uid] for uid in uids]
if not compression_rates:
compression_rates = [0.5] * len(uids)
accumulate_scores, applied_multipliers = self.miner_manager.step_synthetics_compression(
round_id, uids, miner_hotkeys, vmaf_scores,
final_scores, [10] * len(uids), vmaf_thresholds, compression_rates
)
max_length = max(
len(uids),
len(final_scores),
len(vmaf_scores),
len(base_vmaf_scores),
len(reasons),
len(applied_multipliers),
len(accumulate_scores),
)
vmaf_scores.extend([0.0] * (max_length - len(vmaf_scores)))
base_vmaf_scores.extend([None] * (max_length - len(base_vmaf_scores)))
final_scores.extend([0.0] * (max_length - len(final_scores)))
reasons.extend(["No reason provided"] * (max_length - len(reasons)))
compression_rates.extend([0.5] * (max_length - len(compression_rates)))
applied_multipliers.extend([0.0] * (max_length - len(applied_multipliers)))
logger.info(f"Synthetic compression scoring results for {len(uids)} miners")
logger.info(f"Uids: {uids}")
for uid, vmaf_score, base_vmaf_score, final_score, reason, compression_rate, applied_multiplier, vmaf_threshold in zip(
uids, vmaf_scores, base_vmaf_scores, final_scores, reasons, compression_rates, applied_multipliers, vmaf_thresholds
):
base_vmaf_display = f"{base_vmaf_score:.2f}" if base_vmaf_score is not None else "N/A"
logger.info(
f"{uid} ** VMAF NEG: {vmaf_score:.2f} ** VMAF: {base_vmaf_display} "
f"** VMAF Threshold: {vmaf_threshold} ** Compression Rate: {compression_rate:.4f} ** Final: {final_score:.4f} || {reason}"
)
miner_data = {
"validator_uid": self.my_subnet_uid,
"validator_hotkey": self.wallet.hotkey.ss58_address,
"request_type": "Synthetic",
"processing_task_type": "compression",
"miner_uids": uids,
"miner_hotkeys": miner_hotkeys,
"vmaf_scores": vmaf_scores,
"vmaf_thresholds": vmaf_thresholds,
"compression_rates": compression_rates,
"final_scores": final_scores,
"accumulate_scores": accumulate_scores,
"applied_multipliers": applied_multipliers,
"status": reasons,
"task_urls": payload_urls,
"processed_urls": distorted_urls,
"timestamp": timestamp
}
success = send_compression_data_to_dashboard(miner_data)
if success:
logger.info("Compression data successfully sent to dashboard")
else:
logger.info("Failed to send compression data to dashboard")
async def score_organics_upscaling(
self,
uids: list[int],
responses: list[protocol.Synapse],
reference_urls: list[str],
task_types: list[str],
timestamp: str,
distorted_urls: list[str] | None = None,
):
"""Score organic upscaling tasks."""
if distorted_urls is None:
distorted_urls = [response.miner_response.optimized_video_url for response in responses]
combined = list(zip(uids, distorted_urls, reference_urls, task_types))
if not combined:
logger.warning("No organic upscaling responses available for scoring")
return
random.shuffle(combined)
uids, distorted_urls, reference_urls, task_types = map(list, zip(*combined))
num_pairs_to_validate = min(1, len(combined))
selected_indices = random.sample(range(len(combined)), num_pairs_to_validate)
selected_uids = [uids[i] for i in selected_indices]
selected_distorted_urls = [distorted_urls[i] for i in selected_indices]
selected_reference_urls = [reference_urls[i] for i in selected_indices]
selected_task_types = [task_types[i] for i in selected_indices]
logger.info(f"Randomly selected {len(selected_uids)} pairs out of {len(uids)} total pairs for validation")
score_response = await self.score_client_upscaling_organics.post(
"/score_organics_upscaling",
json={
"uids": selected_uids,
"distorted_urls": selected_distorted_urls,
"reference_urls": selected_reference_urls,
"task_types": selected_task_types
},
timeout=180
)
response_data = score_response.json()
scores = response_data.get("final_scores", [])
vmaf_scores = response_data.get("vmaf_scores", [])
pieapp_scores = response_data.get("pieapp_scores", [])
quality_scores = response_data.get("quality_scores", [])
length_scores = response_data.get("length_scores", [])
reasons = response_data.get("reasons", [])
max_length = max(len(selected_uids), len(scores), len(vmaf_scores), len(pieapp_scores), len(reasons))
scores.extend([0.0] * (max_length - len(scores)))
vmaf_scores.extend([0.0] * (max_length - len(vmaf_scores)))
pieapp_scores.extend([0.0] * (max_length - len(pieapp_scores)))
quality_scores.extend([0.0] * (max_length - len(quality_scores)))
length_scores.extend([0.0] * (max_length - len(length_scores)))
reasons.extend(["no reason provided"] * (max_length - len(reasons)))
logger.info(f"organic upscaling scoring results for {len(selected_uids)} miners")
logger.info(f"uids: {selected_uids}")
for uid, vmaf_score, score, reason in zip(selected_uids, vmaf_scores, scores, reasons):
logger.info(f"{uid} ** {vmaf_score:.2f} ** {score:.4f} || {reason}")
round_id = f"organic_upscaling_{int(time.time())}"
logger.info(f"updating miner manager with {len(scores)} miner scores after organic upscaling requests processingβ¦")
accumulate_scores, applied_multipliers = self.miner_manager.step_organic_upscaling(scores, selected_uids, round_id)
miner_hotkeys = [self.metagraph.hotkeys[uid] for uid in selected_uids]
miner_data = {
"validator_uid": self.my_subnet_uid,
"validator_hotkey": self.wallet.hotkey.ss58_address,
"request_type": "Organic",
"processing_task_type": "upscaling",
"miner_uids": selected_uids,
"miner_hotkeys": miner_hotkeys,
"vmaf_scores": vmaf_scores,
"pieapp_scores": pieapp_scores,
"quality_scores": quality_scores,
"length_scores": length_scores,
"final_scores": scores,
"accumulate_scores": accumulate_scores,
"applied_multipliers": applied_multipliers,
"status": reasons,
"task_urls": selected_reference_urls,
"processed_urls": selected_distorted_urls,
"timestamp": timestamp
}
success = send_upscaling_data_to_dashboard(miner_data)
if success:
logger.info("Data successfully sent to dashboard")
else:
logger.info("Failed to send data to dashboard")
async def score_organics_compression(
self,
uids: list[int],
responses: list[protocol.Synapse],
reference_urls: list[str],
vmaf_thresholds: list[float],
target_codecs: list[str],
codec_modes: list[str],
target_bitrates: list[float],
timestamp: str,
distorted_urls: list[str] | None = None,
):
"""Score organic compression tasks."""
if distorted_urls is None:
distorted_urls = [response.miner_response.optimized_video_url for response in responses]
combined = list(zip(uids, distorted_urls, reference_urls, vmaf_thresholds, target_codecs, codec_modes, target_bitrates))
if not combined:
logger.warning("No organic compression responses available for scoring")
return
random.shuffle(combined)
uids, distorted_urls, reference_urls, vmaf_thresholds, target_codecs, codec_modes, target_bitrates = map(list, zip(*combined))
num_pairs_to_validate = min(5, len(combined))
selected_indices = random.sample(range(len(combined)), num_pairs_to_validate)
selected_uids = [uids[i] for i in selected_indices]
selected_distorted_urls = [distorted_urls[i] for i in selected_indices]
selected_reference_urls = [reference_urls[i] for i in selected_indices]
selected_vmaf_thresholds = [vmaf_thresholds[i] for i in selected_indices]
selected_target_codecs = [target_codecs[i] for i in selected_indices]
selected_codec_modes = [codec_modes[i] for i in selected_indices]
selected_target_bitrates = [target_bitrates[i] for i in selected_indices]
logger.info(f"Randomly selected {len(selected_uids)} pairs out of {len(uids)} total pairs for compression validation")
score_response = await self.score_client_compression_organics.post(
"/score_organics_compression",
json={
"uids": selected_uids,
"distorted_urls": selected_distorted_urls,
"reference_urls": selected_reference_urls,
"vmaf_thresholds": selected_vmaf_thresholds,
"target_codecs": selected_target_codecs,
"codec_modes": selected_codec_modes,
"target_bitrates": selected_target_bitrates
},
timeout=180
)
response_data = score_response.json()
scores = response_data.get("final_scores", [])
vmaf_scores = response_data.get("vmaf_scores", [])
base_vmaf_scores = response_data.get("base_vmaf_scores") or []
compression_rates = response_data.get("compression_rates", [])
reasons = response_data.get("reasons", [])
max_length = max(len(selected_uids), len(scores), len(vmaf_scores), len(base_vmaf_scores), len(compression_rates), len(reasons))
scores.extend([0.0] * (max_length - len(scores)))
vmaf_scores.extend([0.0] * (max_length - len(vmaf_scores)))
base_vmaf_scores.extend([None] * (max_length - len(base_vmaf_scores)))
compression_rates.extend([0.5] * (max_length - len(compression_rates)))
reasons.extend(["no reason provided"] * (max_length - len(reasons)))
round_id = f"organic_compression_{int(time.time())}"
logger.info(f"updating miner manager with {len(scores)} miner scores after organic compression requests processingβ¦")
accumulate_scores, applied_multipliers = self.miner_manager.step_organic_compression(scores, selected_uids, vmaf_scores, compression_rates, selected_vmaf_thresholds, round_id)
logger.info(f"organic compression scoring results for {len(selected_uids)} miners")
logger.info(f"uids: {selected_uids}")
for uid, vmaf_score, base_vmaf_score, final_score, reason, compression_rate, applied_multiplier, vmaf_threshold in zip(
selected_uids, vmaf_scores, base_vmaf_scores, scores, reasons, compression_rates, applied_multipliers, selected_vmaf_thresholds
):
base_vmaf_display = f"{base_vmaf_score:.2f}" if base_vmaf_score is not None else "N/A"
logger.info(
f"{uid} ** VMAF NEG: {vmaf_score:.2f} ** VMAF: {base_vmaf_display} "
f"** VMAF Threshold: {vmaf_threshold} ** Compression Rate: {compression_rate:.4f} ** Final: {final_score:.4f} || {reason}"
)
miner_hotkeys = [self.metagraph.hotkeys[uid] for uid in selected_uids]
miner_data = {
"validator_uid": self.my_subnet_uid,
"validator_hotkey": self.wallet.hotkey.ss58_address,
"request_type": "Organic",
"processing_task_type": "compression",
"miner_uids": selected_uids,
"miner_hotkeys": miner_hotkeys,
"vmaf_scores": vmaf_scores,
"vmaf_thresholds": selected_vmaf_thresholds,
"compression_rates": compression_rates,
"final_scores": scores,
"accumulate_scores": accumulate_scores,
"applied_multipliers": applied_multipliers,
"status": reasons,
"task_urls": selected_reference_urls,
"processed_urls": selected_distorted_urls,
"timestamp": timestamp
}
success = send_compression_data_to_dashboard(miner_data)
if success:
logger.info("Compression data successfully sent to dashboard")
else:
logger.info("Failed to send compression data to dashboard")
def filter_miners(self):
min_stake = CONFIG.bandwidth.min_stake
stake_array = self.metagraph.S
miner_uids = [i for i, stake in enumerate(stake_array) if stake < min_stake]
selected_uids, deduped_uid_reasons, deduped_uid_sources = self._deduplicate_uids_by_ip(
miner_uids,
"synthetic miner filter",
)
self.synthetic_deduped_uid_reasons = deduped_uid_reasons
self.synthetic_deduped_uid_sources = deduped_uid_sources
return selected_uids
def _axon_ip_address(self, uid: int) -> str:
axon = self.metagraph.axons[uid]
ip_value = None
for attr in ("ip_str", "external_ip", "ip"):
candidate = getattr(axon, attr, None)
if callable(candidate):
try:
candidate = candidate()
except Exception as e:
logger.debug(f"Unable to resolve axon {attr}: {e}")
candidate = None
if candidate is not None and candidate != "":
ip_value = candidate
break
if ip_value is None:
return ""
if isinstance(ip_value, int):
try:
return str(ipaddress.ip_address(ip_value))
except ValueError:
return str(ip_value)
ip_text = str(ip_value).strip()
if ip_text.startswith("/ipv"):
parts = ip_text.split("/", 2)
if len(parts) == 3:
ip_text = parts[2]
if ip_text.startswith("["):
closing_bracket = ip_text.find("]")
if closing_bracket != -1:
return ip_text[1:closing_bracket]
try:
return str(ipaddress.ip_address(ip_text))
except ValueError:
host, separator, port = ip_text.rpartition(":")
if separator and port.isdigit():
return host
return ip_text
def _uid_coldkey(self, uid: int) -> str:
coldkey = ""
coldkeys = getattr(self.metagraph, "coldkeys", [])
try:
if uid < len(coldkeys):
coldkey = coldkeys[uid]
except Exception as e:
logger.debug(f"Unable to resolve metagraph coldkey for UID {uid}: {e}")
if not coldkey:
try:
coldkey = getattr(self.metagraph.axons[uid], "coldkey", "")
except Exception as e:
logger.debug(f"Unable to resolve axon coldkey for UID {uid}: {e}")
coldkey = ""
return str(coldkey or "").strip()
def _deduplication_reason(self, uid: int, key_type: str, key_value: str, existing_uid: int) -> str:
return (
f"MINER FAILURE: UID {uid} assigned score 0 because it was removed "
f"by synthetic miner deduplication; duplicate {key_type} {key_value} "
f"already used by UID {existing_uid}"
)
def _deduplicate_uids_by_ip(self, uids: list[int], context: str) -> tuple[list[int], dict[int, str], dict[int, int]]:
seen_ips: dict[str, int] = {}
seen_coldkeys: dict[str, int] = {}
deduped_uid_reasons: dict[int, str] = {}
deduped_uid_sources: dict[int, int] = {}
selected = []
for uid in uids:
ip_address = self._axon_ip_address(uid)
if ip_address and ip_address in seen_ips:
existing_uid = seen_ips[ip_address]
logger.warning(
f"Skipping UID {uid} during {context}: duplicate IP {ip_address} "
f"already used by UID {existing_uid}"
)
deduped_uid_reasons[uid] = self._deduplication_reason(
uid, "IP", ip_address, existing_uid
)
deduped_uid_sources[uid] = existing_uid
continue
coldkey = self._uid_coldkey(uid)
if coldkey and coldkey in seen_coldkeys:
existing_uid = seen_coldkeys[coldkey]
logger.warning(
f"Skipping UID {uid} during {context}: duplicate coldkey {coldkey} "
f"already used by UID {existing_uid}"
)
deduped_uid_reasons[uid] = self._deduplication_reason(
uid, "coldkey", coldkey, existing_uid
)
deduped_uid_sources[uid] = existing_uid
continue
if ip_address:
seen_ips[ip_address] = uid
if coldkey:
seen_coldkeys[coldkey] = uid
selected.append(uid)
removed = len(uids) - len(selected)
if removed:
logger.info(f"Removed {removed} duplicate-IP/coldkey UIDs during {context}")
return selected, deduped_uid_reasons, deduped_uid_sources
async def score_deduplicated_synthetic_miners(
self,
deduped_uid_reasons: dict[int, str],
deduped_uid_sources: dict[int, int],
selected_task_types: dict[int, str],
) -> None:
if not deduped_uid_reasons:
return
task_lookup_uids = list({*deduped_uid_reasons.keys(), *deduped_uid_sources.values()})
db_task_types = self.miner_manager.get_miner_processing_task_types(task_lookup_uids)
grouped_uids: dict[str, list[int]] = {"upscaling": [], "compression": []}
for uid in deduped_uid_reasons:
source_uid = deduped_uid_sources.get(uid)
task_type = (
db_task_types.get(uid)
or selected_task_types.get(source_uid)
or db_task_types.get(source_uid)
or "upscaling"
)
if task_type not in grouped_uids:
logger.warning(
f"UID {uid} deduplicated with unknown task_type={task_type}; "
"recording zero score as upscaling"
)
task_type = "upscaling"
grouped_uids[task_type].append(uid)
timestamp = datetime.now(timezone.utc).isoformat()
for task_type, task_uids in grouped_uids.items():
if not task_uids:
continue
score_uids = [
uid
for uid in task_uids
for _query_idx in range(SYNTHETIC_QUERIES_PER_MINER)
]
duplicate_reasons = {
idx: deduped_uid_reasons[uid]
for idx, uid in enumerate(score_uids)
}
round_id = f"deduplicated_{task_type}_{uuid.uuid4()}"
empty_urls = [""] * len(score_uids)
video_ids = [
f"deduplicated_uid_{uid}_query_{query_idx}"
for uid in task_uids
for query_idx in range(SYNTHETIC_QUERIES_PER_MINER)
]
logger.info(
f"Recording {len(score_uids)} score-0 rows for "
f"{len(task_uids)} deduplicated synthetic {task_type} miners"
)
if task_type == "compression":
await self.score_compressions(
score_uids,
[],
[None] * len(score_uids),
empty_urls,
empty_urls,
timestamp,
video_ids,
empty_urls,
[0.0] * len(score_uids),
target_codec="deduplicated",
codec_mode="deduplicated",
target_bitrate=0.0,
round_id=round_id,
distorted_urls=empty_urls,
duplicate_url_reasons=duplicate_reasons,
)
else:
await self.score_upscalings(
score_uids,
[],
empty_urls,
empty_urls,
timestamp,
video_ids,
empty_urls,
[0] * len(score_uids),
["deduplicated"] * len(score_uids),
round_id,
distorted_urls=empty_urls,
duplicate_url_reasons=duplicate_reasons,
)
async def should_process_organic_upscaling(self):
"""Check if organic upscaling tasks should be processed."""
num_organic_upscaling_chunks = get_organic_upscaling_queue_size(self.redis_conn)
if num_organic_upscaling_chunks > 0:
logger.info(f"π· | UPSCALING | The organic_upscaling_queue_size: {num_organic_upscaling_chunks}, processing organic upscaling requests. π·")
await self.process_organic_upscaling_chunks(num_organic_upscaling_chunks)
return True
else:
return False
async def should_process_organic_compression(self):
"""Check if organic compression tasks should be processed."""
num_organic_compression_chunks = get_organic_compression_queue_size(self.redis_conn)
if num_organic_compression_chunks > 0:
logger.info(f"π· | COMPRESSION | The organic_compression_queue_size: {num_organic_compression_chunks}, processing organic compression requests. π·")
await self.process_organic_compression_chunks(num_organic_compression_chunks)
return True
else:
return False
async def process_organic_upscaling_chunks(self, num_organic_chunks):
"""Process organic upscaling chunks."""
organic_start_time = time.time()
needed = min(CONFIG.bandwidth.requests_per_organic_interval, num_organic_chunks)
batch_size = ORGANIC_QUERIES_PER_MINER
miner_count_needed = (needed + batch_size - 1) // batch_size
logger.info(
f"βοΈ | UPSCALING | Start processing {needed} organic chunks "
f"with up to {batch_size} chunks per miner βοΈ"
)
forward_uids = get_organic_forward_uids(self, miner_count_needed, "upscaling", CONFIG.bandwidth.min_stake)
if len(forward_uids) < miner_count_needed:
needed = min(needed, len(forward_uids) * batch_size)
logger.info(
f"There are just {len(forward_uids)} miners available for organic upscaling, "
f"handling {needed} chunks"
)
if needed <= 0 or len(forward_uids) == 0:
logger.warning("No available miners for organic upscaling")
return
task_ids, original_urls, task_types, synapses = await self.challenge_synthesizer.build_organic_upscaling_protocol(
needed, bundle_size=batch_size
)
if len(task_ids) != needed or len(synapses) > len(forward_uids):
logger.error(
f"Mismatch in organic upscaling synapses after building organic protocol: "
f"task_ids={len(task_ids)}, needed={needed}, synapses={len(synapses)}, uids={len(forward_uids)}"
)
return
forward_uids = forward_uids[:len(synapses)]
axon_list = [self.metagraph.axons[uid] for uid in forward_uids]
logger.info("Updating task status to 'processing' for upscaling")
for task_id, original_url in zip(task_ids, original_urls):
await self.update_task_status(task_id, original_url, "processing")
timestamp = datetime.now(timezone.utc).isoformat()
logger.info("π | UPSCALING | Performing polling-based forward operations for upscaling π")
forward_tasks = [
self.call_miner_polling(axon, synapse, uid, VideoUpscalingPollProtocol)
for uid, axon, synapse in zip(forward_uids, axon_list, synapses)
]
raw_responses = await asyncio.gather(*forward_tasks)
responses = [response['result'] for response in raw_responses]
flat_uids = []
processed_urls = []
for batch_idx, response in enumerate(responses):
query_count = len(synapses[batch_idx].miner_payload.reference_video_urls)
response_urls = self._response_video_urls(response, query_count)
for processed_url in response_urls:
flat_uids.append(int(forward_uids[batch_idx]))
processed_urls.append(processed_url)
logger.info(f"Processing organic upscaling chunks with uids: {forward_uids.tolist()}")
logger.info("Updating task status to 'completed' and pushing results for upscaling")
for task_id, original_url, processed_url in zip(task_ids, original_urls, processed_urls):
await self.update_task_status(task_id, original_url, "completed")
await self.push_result(task_id, original_url, processed_url)
asyncio.create_task(
self.score_organics_upscaling(
flat_uids,
[],
original_urls,
task_types,
timestamp,
distorted_urls=processed_urls,
)
)
end_time = time.time()
total_time = end_time - organic_start_time
logger.info(f"π Organic upscaling chunk processing complete in {total_time:.2f} seconds π")
async def process_organic_compression_chunks(self, num_organic_chunks):
"""Process organic compression chunks."""
organic_start_time = time.time()
needed = min(CONFIG.bandwidth.requests_per_organic_interval, num_organic_chunks)
batch_size = ORGANIC_QUERIES_PER_MINER
miner_count_needed = (needed + batch_size - 1) // batch_size
logger.info(
f"βοΈ | COMPRESSION | Start processing {needed} organic chunks "
f"with up to {batch_size} chunks per miner βοΈ"
)
forward_uids = get_organic_forward_uids(self, miner_count_needed, "compression", CONFIG.bandwidth.min_stake)
if len(forward_uids) < miner_count_needed:
needed = min(needed, len(forward_uids) * batch_size)
logger.info(
f"There are just {len(forward_uids)} miners available for organic compression, "
f"handling {needed} chunks"
)
if needed <= 0 or len(forward_uids) == 0:
logger.warning("No available miners for organic compression")
return
(
task_ids,
original_urls,
vmaf_thresholds,
target_codecs,
codec_modes,
target_bitrates,
synapses,
) = await self.challenge_synthesizer.build_organic_compression_protocol(
needed, bundle_size=batch_size
)
if len(task_ids) != needed or len(synapses) > len(forward_uids):
logger.error(
f"Mismatch in organic compression synapses after building organic protocol: "
f"task_ids={len(task_ids)}, needed={needed}, synapses={len(synapses)}, uids={len(forward_uids)}"
)
return
forward_uids = forward_uids[:len(synapses)]
axon_list = [self.metagraph.axons[uid] for uid in forward_uids]
logger.info(f"Processing organic compression chunks with uids: {forward_uids.tolist()}")
logger.info("Updating task status to 'processing' for compression")
for task_id, original_url in zip(task_ids, original_urls):
await self.update_task_status(task_id, original_url, "processing")
timestamp = datetime.now(timezone.utc).isoformat()
logger.info("π | COMPRESSION | Performing polling-based forward operations for compression π")
forward_tasks = [
self.call_miner_polling(axon, synapse, uid, VideoCompressionPollProtocol)
for uid, axon, synapse in zip(forward_uids, axon_list, synapses)
]
raw_responses = await asyncio.gather(*forward_tasks)
responses = [response['result'] for response in raw_responses]
flat_uids = []
processed_urls = []
for batch_idx, response in enumerate(responses):
query_count = len(synapses[batch_idx].miner_payload.reference_video_urls)
response_urls = self._response_video_urls(response, query_count)
for processed_url in response_urls:
flat_uids.append(int(forward_uids[batch_idx]))
processed_urls.append(processed_url)
logger.info("Updating task status to 'completed' and pushing results for compression")
for task_id, original_url, processed_url in zip(task_ids, original_urls, processed_urls):
await self.update_task_status(task_id, original_url, "completed")
await self.push_result(task_id, original_url, processed_url)
asyncio.create_task(
self.score_organics_compression(
flat_uids,
[],
original_urls,
vmaf_thresholds,
target_codecs,
codec_modes,
target_bitrates,
timestamp,
distorted_urls=processed_urls,
)
)
end_time = time.time()
total_time = end_time - organic_start_time
logger.info(f"π Organic compression chunk processing complete in {total_time:.2f} seconds π")
async def update_task_status(self, task_id, original_url, status):
status_update_endpoint = f"{self.organic_gateway_base_url}/admin/task/{task_id}/status"
status_update_payload = {
"status": status,
"original_video_url": original_url
}
try:
async with httpx.AsyncClient() as client:
response = await client.post(status_update_endpoint, json=status_update_payload)
response.raise_for_status()
except httpx.HTTPStatusError as e:
logger.error(f"Error updating status for task {task_id}: {e.response.status_code} - {e.response.text}")
except httpx.RequestError as e:
logger.error(f"Request error updating status for task {task_id}: {e}")
async def push_result(self, task_id, original_url, processed_url):
result_payload = {
"processed_video_url": processed_url,
"original_video_url": original_url,
"score": 0,
"task_id": task_id,
}
try:
async with httpx.AsyncClient() as client:
response = await client.post(self.push_result_endpoint, json=result_payload)
response.raise_for_status()
logger.info(f"Successfully pushed result for task {task_id}")
except httpx.RequestError as e:
logger.error(f"Error pushing result for task {task_id}: {e}")
async def set_weights(self):
self.current_block = self.subtensor.get_current_block()
self.last_update = self.metagraph.last_update[self.uid]
uids, weights = self.miner_manager.weights
(
processed_weight_uids,
processed_weights,
) = bt.utils.weight_utils.process_weights_for_netuid(
uids = uids,
weights=weights,
netuid=self.config.netuid,
subtensor=self.subtensor,
metagraph=self.metagraph,
)
(
uint_uids,
uint_weights,
) = bt.utils.weight_utils.convert_weights_and_uids_for_emit(
uids=processed_weight_uids, weights=processed_weights
)
if self.current_block > self.last_update + CONFIG.SUBNET_TEMPO:
weight_info = list(zip(uint_uids, uint_weights))
weight_info_df = pd.DataFrame(weight_info, columns=["uid", "weight"])
logger.info(f"Weight info:\n{weight_info_df.to_markdown()}")
logger.info("Trying to set weights.")
try:
future = self.set_weights_executor.submit(
self.subtensor.set_weights,
netuid=self.config.netuid,
wallet=self.wallet,
uids=uint_uids,
weights=uint_weights,
)
success, msg = await asyncio.wait_for(asyncio.wrap_future(future), timeout=120)
if not success:
logger.error(f"π Failed to set weights: {msg}")
else:
logger.debug("π Set weights successfully ")
except Exception as e:
logger.error(f"Failed to set weights: {e}")
traceback.print_exc()
else:
logger.info(
f"Not setting weights because current block {self.current_block} is not greater than last update {self.last_update} + tempo {CONFIG.SUBNET_TEMPO}"
)
class WeightSynthesizer:
def __init__(self, validator: Validator):
self.validator = validator
async def run(self):
dev_mode = os.getenv("DEV_MODE", "False").lower() == "true"
while True:
try:
if dev_mode:
logger.info("Not running weight_manager (DEV_MODE)...")
else:
logger.info("Running weight_manager...")
await self.validator.set_weights()
except Exception as e:
logger.error(f"Error in WeightSynthesizer: {e}", exc_info=True)
await asyncio.sleep(60 * 72) # 72 minutes
if __name__ == "__main__":
validator = Validator()
async def main():
try:
if validator.validator_mode is ValidatorMode.COMPETITION:
if not validator.competition_manager.enabled:
logger.warning(
"Competition process is idle because "
"COMPETITION_MODE_ENABLED=false"
)
competition_task = asyncio.Event().wait()
else:
competition_task = validator.run_competition()
await asyncio.gather(
competition_task,
validator.wandb_manager.run_maintenance(),
)
return
weight_synthesizer = WeightSynthesizer(validator)
dev_mode = os.getenv("DEV_MODE", "False").lower() == "true"
await asyncio.sleep(10 if dev_mode else 1300)
set_scheduler_ready(validator.redis_conn, False)
logger.info("Set scheduler readiness flag to False")
await asyncio.gather(
validator.run_synthetic(),
validator.run_organic(),
weight_synthesizer.run(),
validator.wandb_manager.run_maintenance(),
)
finally:
await validator.close()
try:
asyncio.run(main())
except KeyboardInterrupt:
logger.info("Program terminated by user.")
except Exception as e:
logger.error(f"Unhandled exception: {e}", exc_info=True)
finally:
if validator.wandb_manager is not None:
validator.wandb_manager.finish()
import os
import argparse
import time
import uuid
import httpx
import random
import asyncio
import traceback
import pandas as pd
import bittensor as bt
import tempfile
import aiohttp
import ipaddress
import math
from loguru import logger
from dotenv import load_dotenv
from datetime import datetime, timezone
from concurrent.futures import ThreadPoolExecutor
from vidaio_subnet_core.utilities.version import get_version
from vidaio_subnet_core.utilities.storage_client import storage_client
from vidaio_subnet_core import validating, CONFIG, base, protocol
from vidaio_subnet_core.base.config import add_common_config
from vidaio_subnet_core.utilities.wandb_manager import WandbManager
from services.video_scheduler.video_utils import get_trim_video_path, get_perumted_video_path
from vidaio_subnet_core.utilities.uids import get_organic_forward_uids
from vidaio_subnet_core.protocol import (
LengthCheckProtocol,
TaskWarrantProtocol,
TaskType,
VideoCompressionJobProtocol,
VideoCompressionPollProtocol,
VideoUpscalingJobProtocol,
VideoUpscalingPollProtocol,
MinerResponse,
CompetitionInvitationProtocol,
CompetitionSubmissionProtocol,
)
from vidaio_subnet_core.competition.config import (
CompetitionConfig,
CompetitionManifest,
)
from vidaio_subnet_core.competition.artifact_backup import (
CompetitionArtifactBackupError,
CompetitionArtifactBackupService,
CompetitionDatabaseBackupError,
)
from vidaio_subnet_core.competition.build import (
CompetitionBuildService,
ModalImageBuildBackend,
ModalImageBuilder,
)
from vidaio_subnet_core.competition.enrollment import (
CompetitionEnrollmentDispatcher,
CompetitionMinerEndpoint,
)
from vidaio_subnet_core.competition.intake import (
CompetitionSubmissionIntakeService,
RepositoryIntake,
)
from vidaio_subnet_core.competition.manager import CompetitionManager
from vidaio_subnet_core.competition.execution import CompetitionExecutionCoordinator
from vidaio_subnet_core.competition.dataset import ModalVolumeStore
from vidaio_subnet_core.competition.scoring_api import CompetitionScoringClient
from vidaio_subnet_core.competition.modal_runner import (
CompetitionModalRunner,
ModalSandboxBackend,
)
from vidaio_subnet_core.competition.repository import CompetitionRepository
from vidaio_subnet_core.competition.state import CompetitionState
from vidaio_subnet_core.validating.managing.sql_schemas import MinerMetadata, MinerPerformanceHistory, Base
from sqlalchemy import desc, asc, func, select, delete
from sqlalchemy.ext.asyncio import AsyncSession
from datetime import datetime, timedelta
from services.dashboard.server import send_upscaling_data_to_dashboard, send_compression_data_to_dashboard
from services.scoring.compression_score_cache import (
CompressionScoreCache,
find_duplicate_compression_scores,
)
from services.scoring.artifact_cleanup import cleanup_compression_artifacts
from services.video_scheduler.redis_utils import (
get_redis_connection,
get_organic_upscaling_queue_size,
get_organic_compression_queue_size,
set_scheduler_ready
)
from typing import List, Tuple, Any
from enum import Enum, IntEnum
load_dotenv()
METAGRAPH_REFRESH_INTERVAL_SECONDS = float(
os.getenv("METAGRAPH_REFRESH_INTERVAL_SECONDS", 30 * 60)
)
class VMAF_QUALITY_THRESHOLD(IntEnum):
LOW = 85
MEDIUM = 89