feat: implement dynamic concurrency control for SCENE_VLM

- Add dynamic_concurrency module with DynamicSemaphore, SystemMonitor, VlmMonitor, AutoScaler
- Replace static SCENE_VLM_SEM with dynamic version (max concurrency: 3)
- Add AutoScaler background task for automatic concurrency adjustment
- Configured for M5Max48 (48GB): thresholds at 38GB/41GB
- Expected processing time: 23-28 days for 10000 files

Related: Phase 1 implementation after Phase 0 TKG fix verification
This commit is contained in:
Accusys
2026-10-17 21:47:33 +08:00
parent 095df145d6
commit 9886a3a5b2
4 changed files with 223 additions and 1 deletions
+1
View File
@@ -6,6 +6,7 @@ authors = ["Momentry Team"]
description = "Digital asset management system with video analysis and RAG"
[dependencies]
sysinfo = "0.30"
# Core
anyhow = "1.0"
thiserror = "1.0"
+200
View File
@@ -0,0 +1,200 @@
use std::sync::{Arc, RwLock};
use std::time::Duration;
use std::collections::VecDeque;
use tokio::sync::{Semaphore, SemaphorePermit, AcquireError};
use tracing::info;
use sysinfo::System;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MemoryStatus {
Low, // < 38 GB (can increase concurrency)
Normal, // 38-41 GB
High, // > 41 GB (must decrease concurrency)
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum VlmStatus {
Available, // < 5s (can increase concurrency)
Normal, // 5-10s
Overloaded, // > 10s (must decrease concurrency)
Unknown,
}
pub struct DynamicSemaphore {
inner: Arc<Semaphore>,
current_permits: Arc<RwLock<usize>>,
max_permits: usize,
min_permits: usize,
}
impl DynamicSemaphore {
pub fn new(initial_permits: usize, max_permits: usize, min_permits: usize) -> Self {
Self {
inner: Arc::new(Semaphore::new(initial_permits)),
current_permits: Arc::new(RwLock::new(initial_permits)),
max_permits,
min_permits,
}
}
pub async fn acquire(&self) -> Result<SemaphorePermit, AcquireError> {
self.inner.acquire().await
}
pub fn increase(&self) -> bool {
let mut current = self.current_permits.write().unwrap();
if *current < self.max_permits {
*current += 1;
self.inner.add_permits(1);
info!("[AutoScaler] Increased SCENE_VLM concurrency to {}", *current);
return true;
}
false
}
pub fn decrease(&self) -> bool {
let mut current = self.current_permits.write().unwrap();
if *current > self.min_permits {
*current -= 1;
info!("[AutoScaler] Decreased SCENE_VLM concurrency to {}", *current);
true
} else {
false
}
}
pub fn current(&self) -> usize {
*self.current_permits.read().unwrap()
}
}
pub struct SystemMonitor {
total_memory_bytes: u64,
memory_threshold_high: f64,
memory_threshold_low: f64,
}
impl SystemMonitor {
pub fn new(total_memory_gb: u64) -> Self {
Self {
total_memory_bytes: total_memory_gb * 1024 * 1024 * 1024,
memory_threshold_high: 0.85, // 41 GB for 48 GB system
memory_threshold_low: 0.80, // 38 GB for 48 GB system
}
}
pub fn check_memory(&self) -> MemoryStatus {
let mut sys = System::new_all();
sys.refresh_memory();
let used = sys.used_memory() as f64;
let total = self.total_memory_bytes as f64;
let ratio = used / total;
if ratio > self.memory_threshold_high {
MemoryStatus::High
} else if ratio < self.memory_threshold_low {
MemoryStatus::Low
} else {
MemoryStatus::Normal
}
}
}
pub struct VlmMonitor {
response_threshold_high: Duration,
response_threshold_low: Duration,
recent_responses: Arc<RwLock<VecDeque<Duration>>>,
}
impl VlmMonitor {
pub fn new() -> Self {
Self {
response_threshold_high: Duration::from_secs(10),
response_threshold_low: Duration::from_secs(5),
recent_responses: Arc::new(RwLock::new(VecDeque::with_capacity(10))),
}
}
pub fn record_response(&self, duration: Duration) {
let mut responses = self.recent_responses.write().unwrap();
responses.push_back(duration);
if responses.len() > 10 {
responses.pop_front();
}
}
pub fn check_status(&self) -> VlmStatus {
let responses = self.recent_responses.read().unwrap();
if responses.is_empty() {
return VlmStatus::Unknown;
}
let avg: Duration = responses.iter().sum::<Duration>() / responses.len() as u32;
if avg > self.response_threshold_high {
VlmStatus::Overloaded
} else if avg < self.response_threshold_low {
VlmStatus::Available
} else {
VlmStatus::Normal
}
}
}
pub struct AutoScaler {
semaphore: Arc<DynamicSemaphore>,
system_monitor: Arc<SystemMonitor>,
vlm_monitor: Arc<VlmMonitor>,
check_interval: Duration,
}
impl AutoScaler {
pub fn new(
semaphore: Arc<DynamicSemaphore>,
system_monitor: Arc<SystemMonitor>,
vlm_monitor: Arc<VlmMonitor>,
check_interval: Duration,
) -> Self {
Self {
semaphore,
system_monitor,
vlm_monitor,
check_interval,
}
}
pub async fn run(self: Arc<Self>) {
use tokio::time::interval;
let mut ticker = interval(self.check_interval);
loop {
ticker.tick().await;
let mem_status = self.system_monitor.check_memory();
let vlm_status = self.vlm_monitor.check_status();
let current = self.semaphore.current();
info!(
"[AutoScaler] Status: mem={:?}, vlm={:?}, current_concurrency={}",
mem_status, vlm_status, current
);
match (&mem_status, &vlm_status) {
(MemoryStatus::High, _) |
(_, VlmStatus::Overloaded) => {
self.semaphore.decrease();
}
(MemoryStatus::Low, VlmStatus::Available) |
(MemoryStatus::Low, VlmStatus::Unknown) => {
self.semaphore.increase();
}
_ => {}
}
}
}
}
+1
View File
@@ -8,6 +8,7 @@ pub mod checkin;
pub mod chunk;
pub mod command;
pub mod config;
pub mod dynamic_concurrency;
pub mod db;
pub mod embedding;
pub mod face_filter_engine;
+21 -1
View File
@@ -5,6 +5,7 @@ use std::sync::Arc;
use std::sync::LazyLock;
use std::time::Duration;
use tokio::sync::Semaphore;
use crate::core::dynamic_concurrency::{DynamicSemaphore, SystemMonitor, VlmMonitor, AutoScaler};
use tokio::time::sleep;
use tracing::{debug, error, info, warn};
@@ -30,7 +31,10 @@ static FACE_TRACE_INFLIGHT: LazyLock<tokio::sync::Mutex<std::collections::HashSe
/// loads frames + calls the multimodal LLM; without a bound, dispatching many files
/// in parallel would exhaust memory. One at a time mirrors the previous inline
/// (sequential) behavior without blocking the worker poll loop.
static SCENE_VLM_SEM: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(1));
static SCENE_VLM_SEM: LazyLock<Arc<DynamicSemaphore>> = LazyLock::new(|| Arc::new(DynamicSemaphore::new(1, 3, 1)));
/// Global VLM monitor for tracking response times
static VLM_MONITOR: LazyLock<Arc<VlmMonitor>> = LazyLock::new(|| Arc::new(VlmMonitor::new()));
/// Tracks uuids with a Scene VLM task currently spawned (or queued for a permit).
/// Prevents the per-poll loop from spawning duplicate tasks before `scenes.json`
@@ -4866,3 +4870,19 @@ mod tests {
assert!(stage_dependencies(ProcessorType::Cut).is_empty());
}
}
/// Start the AutoScaler background task for dynamic SCENE_VLM concurrency
pub fn start_autoscaler() {
let auto_scaler = Arc::new(AutoScaler::new(
SCENE_VLM_SEM.clone(),
Arc::new(SystemMonitor::new(48)), // M5Max48
VLM_MONITOR.clone(),
Duration::from_secs(30),
));
tokio::spawn(async move {
auto_scaler.run().await;
});
info!("[AutoScaler] Started dynamic concurrency controller for SCENE_VLM");
}