Label Studio ML Backend

repository·master·Indexed 22 days ago

https://github.com/humansignal/label-studio-ml-backend

An SDK for wrapping machine learning models into a web server that integrates with Label Studio for automated labeling, pre-annotation, and interactive model training. It supports deployment via Docker or local Python environments and includes examples for BERT-based text classification, Deepgram Text-to-Speech annotation, and Docling Serve integration.

Tokens
46.2K
Snippets
121
Records
192
Agent score
77%

What's inside label-studio-ml-backend

  1. What is the Label Studio ML backend?

    master

    The Label Studio ML backend is an SDK that allows you to wrap machine learning code into a web server. This server can be connected to a running Label Studio instance to automate labeling tasks through pre-annotations, interactive labeling, or model training.

    Note: If you only need to load static pre-annotated data, you should use Label Studio's import pre-annotated data feature instead of running an ML backend.

  2. Map Label Studio labels to YOLO model names

    master

    Because ML model labels often differ from the human-readable labels used in Label Studio, you must define a mapping.

    1. Default Mapping: By default, the YOLO ML backend uses the same name (or a lowercased version) as specified in the value attribute of your Label Studio tag.

      • Example: <Choice value="Jeep"/> maps to jeep in the model.
    2. Precise Mapping: For more control, use the predicted_values attribute to map a single Label Studio label to one or more specific labels from the ML model. This is a comma-separated list.

    <Choice value="Car" predicted_values="jeep,cab,limousine"/>

    Tip: To find the exact names used by your YOLO model, check the ML model logs at the INFO logging level when the backend starts, or refer to YOLO_CLASSES.md in the repository.

  3. Understand Annotation Types: Range vs. Instant

    master

    The backend supports two distinct ways of annotating time series data:

    1. Range Annotations

      • Use case: Events with a duration (e.g., "Running from 10s to 30s").
      • Creation: Dragging across the time series.
      • Technical behavior: startend, and instant is set to false.
    2. Instant Annotations

      • Use case: Point events or specific moments (e.g., "Fall detected at 15s").
      • Creation: Double-clicking a specific point.
      • Technical behavior: start = end, and instant is set to true.

    Note: Instant labels often create highly imbalanced datasets. The backend uses a balanced learning approach (class-weighted loss and balanced accuracy monitoring) to handle this.

  4. Understand the TimelineLabelsModel architecture

    master

    The TimelineLabelsModel is the primary interface for the <TimelineLabels> control tag in Label Studio. It extends ControlModel and manages two distinct operational modes for temporal video multi-label classification: Simple mode and Trainable mode.

    Operational Modes

    1. Simple Mode (self.trainable == False): Uses pre-trained YOLO classes for prediction without additional training. It relies on cached_yolo_predict to extract probabilities from frames and converts them into timeline labels.

    2. Trainable Mode (self.trainable == True): Uses a custom-trained LSTM neural network to capture temporal dependencies. It extracts features via cached_feature_extraction, loads a trained classifier, and uses the LSTM to predict probabilities across the video sequence.

    Key Methods in timeline_labels.py

    • predict_regions(video_path): The entry point for prediction requests. It routes the request to either create_timelines_simple or create_timelines_trainable based on the trainable attribute.
    • fit(event, data, **kwargs): The entry point for incremental training. It is triggered by Label Studio events like ANNOTATION_CREATED or ANNOTATION_UPDATED to update the LSTM model with new human-labeled data.
  5. Compare SAM Model Architectures (AdvancedSAM vs ONNXSAM)

    master

    Choose the model based on your hardware and accuracy requirements:

    Advanced Segment Anything Model

    Supports mixing different prompt types (rectangles, positive/negative keypoints) and using MobileSAM.

    • MobileSAM: Lightweight, runs on laptops/CPU, fast inference (<1s), but lower accuracy.
    • Original SAM: High accuracy, supports mixed prompts, but requires good GPUs and takes longer (~2s for embeddings).

    ONNX Segment Anything Model

    • Pros: Much faster than Advanced SAM.
    • Cons: Only supports one smart label per prediction; image size must be defined before generating the model and cannot be easily generalized to different image sizes.
  6. How Project Isolation works in the Time Series Segmenter

    master

    The backend provides multi-tenant support by maintaining separate trained models for each Label Studio project. This prevents cross-project interference and ensures data isolation.

    Key Mechanisms:

    • Model Storage: Each project receives a unique model file named model_project_{project_id}.pt (e.g., model_project_47.pt).
    • Training: The backend identifies the source project ID from annotation webhook events to save the correct model.
    • Prediction: The backend detects the project ID from the task context or request metadata to load the corresponding model. If no project information is available, it falls back to a default model (model_project_0.pt).
    • Benefits: Sensitive data from Project A cannot influence the model for Project B, and each model optimizes specifically for its own project's labeling configuration.
  7. Understand the SAM2 Wire Protocol: Prewarm and Predict modes

    master

    The SAM2 backend multiplexes two modes through the /predict endpoint, determined by the context.event value in the request parameters.

    Prewarm Mode

    Used to cache frames in a window around a specific frame to reduce latency during navigation.

    • Request context.event: prewarm
    • Response: Returns status and information about cached and pending frames.

    Predict Mode

    Used for actual inference based on user prompts (clicks or boxes).

    • Request context.event: (Implicitly triggered by presence of result in context)
    • Response: Returns a standard PredictionValue containing the segmentation results (bitmasks, rectangles, or polygons).
    ### Prewarm Request Example
    ```json
    {
      "tasks": [{"id": 1, "data": {"video": "..."}}],
      "params": {
        "context": {
          "event": "prewarm",
          "frame": 42,
          "window": 20,
          "direction": "forward"
        }
      }
    }

    Predict Request Example

    {
      "tasks": [{"id": 1, "data": {"video": "..."}}],
      "params": {
        "context": {
          "frame": 42,
          "result": [
            {"type": "keypointlabels", "value": {"x": 45.2, "y": 30.1, "positive": true}},
            {"type": "keypointlabels", "value": {"x": 60.0, "y": 55.0, "positive": false}}
          ]
        }
      }
    }
  8. Map keypoints to specific labels using `model_index`

    master

    To ensure detected keypoints are correctly identified in the Label Studio interface, use the model_index and predicted_values attributes within your Label tags.

    For standard YOLO pose models, the mapping follows this index pattern:

    • 0: Nose
    • 1: Left Eye
    • 2: Right Eye
    • 3: Left Ear
    • 4: Right Ear
    • 5: Left Shoulder
    • 6: Right Shoulder
    • 7: Left Elbow
    • 8: Right Elbow
    • 9: Left Wrist
    • 10: Right Wrist
    • 11: Left Hip
    • 12: Right Hip
    • 13: Left Knee
    • 14: Right Knee
    • 15: Left Ankle
    • 16: Right Ankle
    <Label value="left_eye" predicted_values="person" model_index="1" />
    <Label value="right_eye" predicted_values="person" model_index="2" />
  9. How Control Models map YOLO to Label Studio annotations

    master

    Control models are specialized subclasses of ControlModel that translate YOLO model outputs into Label Studio-compatible annotation formats. Each model is responsible for a specific ControlTag found in the Label Studio configuration.

    Annotation TypeControl ModelPurpose
    Bounding BoxesRectangleLabelsModelHandles axis-aligned or oriented (OBB) rectangles for images.
    PolygonsPolygonLabelsModelConverts segmentation masks into polygon coordinates.
    ClassificationChoicesModelMaps classification outputs to Label Studio Choices format.
    KeypointsKeyPointLabelsModelConverts pose estimation outputs into keypoint annotations.
    Video TrackingVideoRectangleModelUses YOLO tracking to generate bounding boxes across video frames.
    TimelinesTimelineLabelsModelSupports temporal event annotations.