Files
leleka/control-plane/src/vision/encoder.rs
T

292 lines
11 KiB
Rust

//! Moved out of the parent module by STRA-338: impl Vision.
#[allow(unused_imports)]
use super::*;
/// The token count in an `OK <tokens>` reply of the encoder; an `ERR` reply or a closed pipe is an invalid image.
fn reply_tokens(line: &str) -> Result<usize, VisionError> {
if !line.starts_with("OK") {
return Err(VisionError::Invalid(format!(
"the image could not be read: {}",
match line.strip_prefix("ERR") {
Some(_) => line.get(4..).unwrap_or(""),
None => "the vision encoder stopped",
}
)));
}
line.split_whitespace()
.nth(1)
.and_then(|n| n.parse::<usize>().ok())
.ok_or_else(|| VisionError::Failed(format!("unexpected vision encoder reply: {line}")))
}
/// Wait for the `READY` line of a freshly started encoder; the process is killed when it does not come.
async fn await_ready(
child: &mut Child,
lines: &mut tokio::io::Lines<BufReader<ChildStdout>>,
) -> Result<(), VisionError> {
let first = match timeout(START_TIMEOUT, lines.next_line()).await {
Ok(Ok(Some(line))) => line,
Ok(Ok(None)) => String::new(),
Ok(Err(e)) => {
return Err(VisionError::Failed(format!(
"the vision encoder did not start: {e}"
)));
}
Err(_) => {
let _ = child.kill().await;
return Err(VisionError::Failed(
"the vision encoder did not start: no READY line in time".into(),
));
}
};
if !first.starts_with("READY") {
let _ = child.kill().await;
return Err(VisionError::Failed(format!(
"the vision encoder did not start: {}",
first.trim()
)));
}
Ok(())
}
impl Vision {
/// Start the encoder and wait for its `READY` line (`Vision.__init__`).
pub async fn start(config: VisionConfig) -> Result<Arc<Self>, VisionError> {
let vision = Self::unstarted(config)?;
{
let mut inner = vision.inner.lock().await;
vision.spawn(&mut inner).await?;
}
Ok(Arc::new(vision))
}
/// A client whose process is started by the first [`Vision::restart`] or [`Vision::ensure_running`].
pub fn unstarted(config: VisionConfig) -> Result<Self, VisionError> {
let dir = std::env::temp_dir().join(format!(
"strata-vision-{}-{}",
std::process::id(),
NEXT_DIR.fetch_add(1, Ordering::Relaxed)
));
std::fs::create_dir_all(&dir)
.map_err(|e| VisionError::Failed(format!("cannot create {}: {e}", dir.display())))?;
Ok(Self {
config,
dir,
inner: Mutex::new(Inner::default()),
stopped: AtomicBool::new(true),
serial: AtomicU64::new(0),
gate: Arc::new(Mutex::new(())),
})
}
pub fn dir(&self) -> &Path {
&self.dir
}
pub(super) async fn spawn(&self, inner: &mut Inner) -> Result<(), VisionError> {
let mut child = self.launch()?;
let stdin = child.stdin.take().expect("piped encoder stdin");
let stdout = child.stdout.take().expect("piped encoder stdout");
let mut lines = BufReader::new(stdout).lines();
await_ready(&mut child, &mut lines).await?;
inner.proc = Some(Proc {
child,
stdin,
lines,
});
self.stopped.store(false, Ordering::Release);
Ok(())
}
/// The encoder process with piped stdin and stdout.
fn launch(&self) -> Result<Child, VisionError> {
let mut command = Command::new(&self.config.exe);
command
.args(self.config.args())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.kill_on_drop(true);
for (name, value) in self.config.env() {
command.env(name, value);
}
command.spawn().map_err(|e| {
VisionError::Failed(format!(
"the vision encoder did not start: {}: {e}",
self.config.exe.display()
))
})
}
/// `Vision.alive`: started, not unloaded, and the process still runs.
pub async fn alive(&self) -> bool {
if self.stopped.load(Ordering::Acquire) {
return false;
}
let mut inner = self.inner.lock().await;
inner
.proc
.as_mut()
.is_some_and(|proc| matches!(proc.child.try_wait(), Ok(None)))
}
pub(super) async fn close_inner(inner: &mut Inner) {
let Some(mut proc) = inner.proc.take() else {
return;
};
let quit = async {
proc.stdin.write_all(b"QUIT\n").await.ok()?;
proc.stdin.flush().await.ok()?;
drop(proc.stdin);
timeout(Duration::from_secs(10), proc.child.wait())
.await
.ok()?
.ok()
};
if quit.await.is_none() {
let _ = proc.child.kill().await;
}
}
/// `Vision.close`: ask the encoder to quit, kill it if it does not.
pub async fn close(&self) {
let mut inner = self.inner.lock().await;
Self::close_inner(&mut inner).await;
self.stopped.store(true, Ordering::Release);
}
/// `Vision.unload`: stop the process (its VRAM or RAM goes back); the encoded images stay cached on disk.
pub async fn unload(&self) {
self.close().await;
}
/// `Vision.restart`: start the process again after an unload or a death; the cache is kept.
pub async fn restart(&self) -> Result<(), VisionError> {
let mut inner = self.inner.lock().await;
if let Some(mut proc) = inner.proc.take() {
let _ = proc.child.kill().await;
}
self.spawn(&mut inner).await
}
/// `Service.ensure_loaded`'s vision step: start the encoder again unless it runs. Done before the engine starts
/// (a GPU encoder takes its VRAM first, the engine sizes its cache from what is left).
pub async fn ensure_running(&self) -> Result<(), VisionError> {
if self.alive().await {
return Ok(());
}
crate::elog!("starting the vision encoder again ...");
self.restart().await
}
/// `Vision.load`: the bytes behind an image source (a `data:` URL, an http(s) URL or a local path).
pub async fn load(source: &str) -> Result<Vec<u8>, VisionError> {
if let Some(rest) = source.strip_prefix("data:") {
let (_, payload) = rest.split_once(',').ok_or_else(|| {
VisionError::Invalid("an image data: URL needs a comma before its data".into())
})?;
return policy::b64decode(payload).map_err(VisionError::Invalid);
}
if source.starts_with("http://") || source.starts_with("https://") {
return fetch(source).await;
}
let path = source.strip_prefix("file://").unwrap_or(source);
if !path.is_empty() && tokio::fs::metadata(path).await.is_ok_and(|m| m.is_file()) {
return tokio::fs::read(path)
.await
.map_err(|e| VisionError::Invalid(format!("the image could not be read ({e})")));
}
Err(VisionError::Invalid(
"an image must be a data: URL, an http(s) URL or a local file path".into(),
))
}
/// `Vision.normalize` without an image library: the formats `strata-vision`'s decoder reads pass through.
pub fn normalize(data: Vec<u8>) -> Result<Vec<u8>, VisionError> {
if policy::is_native_image_format(&data) {
Ok(data)
} else {
Err(VisionError::Invalid(
"this image format is not supported (JPEG, PNG, BMP and GIF are; convert WebP, TIFF, AVIF, ... first)"
.into(),
))
}
}
/// `Vision.encode`: the embeddings file of an image and its number of image tokens; the same picture
/// (by content) is encoded once.
pub async fn encode(&self, source: &str) -> Result<Encoded, VisionError> {
let data = Self::normalize(Self::load(source).await?)?;
let key = hex::encode(Sha256::digest(&data))[..32].to_owned();
let mut inner = self.inner.lock().await;
if let Some((_, hit)) = inner.cache.iter().find(|(k, _)| *k == key) {
return Ok(hit.clone());
}
let image = self.dir.join(format!("{key}.img"));
let out = self.dir.join(format!("{key}.sve"));
tokio::fs::write(&image, &data)
.await
.map_err(|e| VisionError::Failed(format!("cannot write {}: {e}", image.display())))?;
let reply = Self::exchange(&mut inner, &image, &out).await;
let _ = tokio::fs::remove_file(&image).await; // #352: also when the encoder's pipe is gone
let tokens = reply_tokens(&reply?)?;
let encoded = Encoded { path: out, tokens };
inner.cache.push_back((key, encoded.clone()));
if inner.cache.len() > CACHE_LIMIT
&& let Some((_, old)) = inner.cache.pop_front()
{
let _ = tokio::fs::remove_file(&old.path).await; // oldest first
}
Ok(encoded)
}
/// One `ENC` line and its reply (`""` when the encoder's output ended).
pub(super) async fn exchange(
inner: &mut Inner,
image: &Path,
out: &Path,
) -> Result<String, VisionError> {
let proc = inner
.proc
.as_mut()
.ok_or_else(|| VisionError::Failed("the vision encoder is not running".into()))?;
let line = format!("ENC {} {}\n", image.display(), out.display());
proc.stdin
.write_all(line.as_bytes())
.await
.map_err(|e| VisionError::Failed(format!("the vision encoder is gone: {e}")))?;
proc.stdin
.flush()
.await
.map_err(|e| VisionError::Failed(format!("the vision encoder is gone: {e}")))?;
match proc.lines.next_line().await {
Ok(Some(reply)) => Ok(reply.trim().to_owned()),
Ok(None) => Ok(String::new()),
Err(e) => Err(VisionError::Failed(format!(
"the vision encoder is gone: {e}"
))),
}
}
/// The concatenation of the images' SVE1 files in prompt order: `GENI`'s embeddings file for one request.
pub async fn combine(&self, images: &[Encoded]) -> Result<(PathBuf, Keep), VisionError> {
let name = format!(
"req-{:x}-{:x}.sve",
std::process::id(),
self.serial.fetch_add(1, Ordering::Relaxed)
);
let path = self.dir.join(name);
let mut bytes = Vec::new();
for image in images {
bytes.extend(tokio::fs::read(&image.path).await.map_err(|e| {
VisionError::Failed(format!("cannot read {}: {e}", image.path.display()))
})?);
}
tokio::fs::write(&path, bytes)
.await
.map_err(|e| VisionError::Failed(format!("cannot write {}: {e}", path.display())))?;
Ok((path.clone(), Keep(Some(Arc::new(TempFile(path))))))
}
}