Infinity

repository·main·Indexed 25 days ago

https://github.com/michaelfeil/infinity

A high-performance REST API server for deploying HuggingFace models, including text embeddings, rerankers, and multi-modal models like CLIP, CLAP, and ColPali. Optimized for low latency and high throughput using TensorRT and CTranslate2, it supports deployments across various infrastructures including AWS Inferentia/Trainium, Baseten, Modal, KubeAI, SAP Core AI, and Vast.ai.

Tokens
23.2K
Snippets
53
Records
131
Agent score
83%

What's inside Infinity

  1. Overview of Infinity

    main

    Infinity is a high-throughput, low-latency REST API designed for serving various machine learning models, including:

    • Text-embeddings
    • Reranking models
    • CLIP, CLAP, and ColPali (multi-modal models)

    Key features include:

    • HuggingFace Integration: Deploy any embedding, reranking, CLIP, or sentence-transformer model from HuggingFace.
    • High-Performance Backends: Built on PyTorch, optimum (ONNX/TensorRT), and CTranslate2. It utilizes FlashAttention and supports multiple accelerators including NVIDIA CUDA, AMD ROCM, CPU, AWS INF2, and Apple MPS.
    • Orchestration: Supports multi-modal and multi-model setups, allowing you to mix and match multiple models within a single instance.
    • OpenAI Compatibility: The API is OpenAPI aligned to OpenAI's API specifications, making it easy to integrate with existing tools.
  2. External Deployment Integrations

    main

    Infinity supports several third-party deployment platforms:

    • Modal Labs: Deployment examples and GitHub Actions pipelines are available in the infra/modal directory of the repository.
    • Runpod.io: A dedicated guide for Serverless deployment is available via the runpod-workers/worker-infinity-text-embeddings repository.
    • Bento: Deployment via BentoML is supported; see the BentoInfinity example repository.
  3. Build Docker images for offline mode or custom packages

    main

    To run Infinity in offline environments or with models requiring specific Python dependencies (e.g., nomic-ai/nomic-embed-text-v1.5), you should build a custom image using docker buildx build. This allows you to pre-download models and install extra packages during the build stage.

    Key build arguments:

    • --build-arg MODEL_NAME: The model ID to download.
    • --build-arg ENGINE: The inference engine (e.g., torch).
    • --build-arg EXTRA_PACKAGES: A string of additional Python packages to install (e.g., "torch_geometric").

    Target the production-with-download stage in the Dockerfile.

    # clone the repo
    git clone https://github.com/michaelfeil/infinity
    git checkout tags/0.0.52
    cd libs/infinity_emb
    
    # build download stage using docker buildx buildkit.
    docker buildx build --target=production-with-download \
    --build-arg MODEL_NAME=michaelfeil/bge-small-en-v1.5 --build-arg ENGINE=torch \
    -f Dockerfile -t infinity-model-small .
    
    # Example with extra packages:
    # docker buildx build --target=production-with-download \
    # --build-arg MODEL_NAME=michaelfeil/bge-small-en-v1.5 --build-arg ENGINE=torch \
    # --build-arg EXTRA_PACKAGES="torch_geometric" \
    # -f Dockerfile -t infinity-model-small .
  4. Integrate Infinity with Langchain using Local Inference

    main

    Use the InfinityEmbeddingsLocal class to run embeddings locally without an external API server.

    Important Usage Notes:

    • Lifecycle Management: You MUST use the async with statement to manage the engine. This starts and stops the batching engine correctly. Avoid frequently closing and starting the engine; instead, keep it running for the duration of your tasks.
    • Manual Control: If you need more granular control, you can manually call await embeddings.__aenter__() and await embeddings.__aexit__().
    • Hardware: Set device="cuda" for AMD/Nvidia GPUs via torch.
    from langchain.embeddings.infinity import InfinityEmbeddingsLocal
    from langchain.docstore.document import Document
    
    embeddings = InfinityEmbeddingsLocal(
        model="sentence-transformers/all-MiniLM-L6-v2",
        # revision
        revision=None,
        # best to keep at 32
        batch_size=32,
        # for AMD/Nvidia GPUs via torch
        device="cuda",
        # warm up model before execution,
    )
    
    documents = [Document(page_content="Hello world!", metadata={"source": "unknown"})]
    
    # important: use engine inside of `async with` statement to start/stop the batching engine.
    async with embeddings:
        # avoid closing and starting the engine often.
        # rather keep it running.
        # you may call `await embeddings.__aenter__()` and `__aexit__()`
        # if you are sure when to manually start/stop execution` in a more granular way
        documents_embedded = await embeddings.aembed_documents(documents)
        query_result = await embeddings.aembed_query(query)
        print("embeddings created successful")
    print(documents_embedded, query_result)
  5. Deploy Infinity via Modal

    main

    To deploy the Infinity serverless deployment using Modal, clone the repository, install the specific version of modal required, and run the deployment command targeting the webserver. This deployment utilizes Nvidia L4/A100 hardware via Modal.com.

    git clone https://github.com/michaelfeil/infinity
    pip install modal==0.66.0
    modal deploy --env main infra.modal.webserver
  6. Deploy Infinity to AWS ECS with Neuron support

    main

    To deploy Infinity on AWS ECS, your task definition must include specific configurations for Neuron hardware access:

    1. Placement Constraints: Ensure tasks are placed on instances with the correct type (e.g., inf2.xlarge).
    2. Linux Parameters: You must map the device /dev/neuron0 from the host to the container and grant IPC_LOCK capabilities.
    3. Port Mappings: Define the port used by the infinity_emb process.
    {
        "family": "ecs-infinity-neuron",
        "requiresCompatibilities": ["EC2"],
        "placementConstraints": [
            {
                "type": "memberOf",
                "expression": "attribute:ecs.os-type == linux"
            },
            {
                "type": "memberOf",
                "expression": "attribute:ecs.instance-type == inf2.xlarge"
            }
        ],
        "executionRoleArn": "${YOUR_EXECUTION_ROLE}",
        "containerDefinitions": [
            {
                "entryPoint": ["infinity_emb", "v2"],
                "portMappings": [
                    {
                        "hostPort": 7997,
                        "protocol": "tcp",
                        "containerPort": 7997
                    }
                ],
                "linuxParameters": {
                    "devices": [
                        {
                            "containerPath": "/dev/neuron0",
                            "hostPath": "/dev/neuron0",
                            "permissions": ["read", "write"]
                        }
                    ],
                    "capabilities": {
                        "add": ["IPC_LOCK"]
                    }
                },
                "cpu": 0,
                "memoryReservation": 1000,
                "image": "infinity-neuron:latest",
                "essential": true,
                "name": "infinity-neuron"
            }
        ]
    }
  7. Configure automatic Modal deployment via GitHub Actions

    main

    Automatic integration for Modal deployments can be configured using the GitHub Actions pipeline defined in the repository. Refer to the workflow file for the specific pipeline configuration.

    https://github.com/michaelfeil/infinity/blob/main/.github/workflows/release_modal_com.yaml
  8. Run Infinity using Docker on AWS Neuron

    main

    If you prefer a containerized approach, you can build and run Infinity using Docker. Note that the host must have the Neuron driver installed. This method is considered less tested than the direct AMI approach.

    Build

    Build the image using the specific Neuron Dockerfile located in infra/aws_neuron/.

    Run

    Pass the --device=/dev/neuron0 flag to the docker run command to grant access to the Neuron hardware.

    # Build from source
    git clone https://github.com/michaelfeil/infinity
    cd infinity
    docker buildx build -t infinity-neuron -f ./infra/aws_neuron/Dockerfile.neuron .
    
    # Run on EC2
    docker run -it --rm --device=/dev/neuron0 infinity-neuron \
      v2 --model-id BAAI/bge-small-en-v1.5 --batch-size 8
  9. Install development dependencies for infinity_emb

    main

    To set up a development environment for the infinity_emb library, use Poetry 1.8.1 with Python 3.11 on Ubuntu 22.04. This installs all extras along with linting and testing dependencies.

    cd libs/infinity_emb
    poetry install --extras all --with lint,test