Informers

repository·master·Indexed 20 days ago

https://github.com/ankane/informers

A Ruby library providing fast transformer inference using ONNX Runtime. It enables local execution of embedding, reranking, text, vision, and audio models through a pipeline abstraction. Supported tasks include sentiment analysis, NER, image classification, object detection, and text generation. The library includes AutoModel classes for various architectures and supports hardware acceleration via CPU, CUDA, and CoreML.

Tokens
12K
Snippets
38
Records
53
Agent score
70%

What's inside informers

  1. How Informers pipelines work

    master

    Informers uses a pipeline abstraction to perform various machine learning tasks. You initialize a pipeline by specifying a task type (e.g., embedding, reranking, text-generation) and optionally a model identifier. Once initialized, the pipeline object is a callable that accepts inputs (text, images, or audio) and returns the processed results.

    Common task types include:

    • Text: embedding, reranking, ner, sentiment-analysis, question-answering, zero-shot-classification, text-generation, text2text-generation, translation, summarization, fill-mask, feature-extraction.
    • Vision: image-classification, zero-shot-image-classification, image-segmentation, object-detection, zero-shot-object-detection, depth-estimation, image-to-image, image-feature-extraction.
    • Audio: audio-classification.
    • Multimodal: image-to-text, document-question-answering.
    # Example of a text embedding pipeline
    model = Informers.pipeline("embedding", "sentence-transformers/all-MiniLM-L6-v2")
    embeddings = model.(["Hello world", "How are you?"])
  2. How ImageFeatureExtractor processes images

    master

    The ImageFeatureExtractor#preprocess method executes a sequence of transformations to prepare an image for a model. The typical lifecycle is:

    1. Color Conversion: Converts to RGB or Grayscale based on config.
    2. Resizing: Applies resize or thumbnail logic.
    3. Cropping: Applies center_crop if configured.
    4. Pixel Manipulation:
      • Rescales pixel values (e.g., to [0, 1]).
      • Normalizes using image_mean and image_std.
      • Applies padding if do_pad is enabled.
    5. Format Conversion: Converts the data from HWC (Height, Width, Channels) to CHW (Channels, Height, Width) format.

    The call method allows processing an array of images, returning a hash containing pixel_values (stacked tensors), original_sizes, and reshaped_input_sizes.

  3. Authenticate with Hugging Face using `HF_TOKEN`

    master

    When downloading files from Hugging Face (huggingface.co or hf.co), Informers automatically checks for the HF_TOKEN environment variable. If present, it is added to the request headers as a Bearer token:

    Authorization: Bearer <YOUR_TOKEN>

    This allows the library to access private or gated models on the Hugging Face Hub without manual header configuration.

  4. Understand ModelOutput structures

    master

    Models in this library return specialized output objects that inherit from ModelOutput. These objects allow for easy access to model predictions via key-based lookup or specific reader methods. Common output types include:

    • Seq2SeqLMOutput: Contains logits, past_key_values, encoder_outputs, decoder_attentions, and cross_attentions.
    • SequenceClassifierOutput: Contains logits.
    • TokenClassifierOutput: Contains logits.
    • MaskedLMOutput: Contains logits.
    • QuestionAnsweringModelOutput: Contains start_logits and end_logits.
    • DetrObjectDetectionOutput: Contains logits and pred_boxes.
    • DetrSegmentationOutput: Contains logits, pred_boxes, and pred_masks.
  5. Requirements for Vision and Audio pipelines

    master

    Certain pipelines require external system dependencies to handle specific file formats:

    • Vision Pipelines (e.g., image-classification, object-detection): Requires the ruby-vips gem to load images.
    • Audio Pipelines (e.g., audio-classification): Requires ffmpeg installed on the system to load audio files.
  6. Use reranking pipelines

    master

    Reranking pipelines take a query and a list of documents, returning a score or ranked result that indicates how relevant the documents are to the query. This is often used as a second stage after an initial retrieval step.

    Example using mixedbread-ai/mxbai-rerank-base-v1:

    query = "How many people live in London?"
    docs = ["Around 9 Million people live in London", "London is known for its financial district"]
    
    model = Informers.pipeline("reranking", "mixedbread-ai/mxbai-rerank-base-v1")
    result = model.(query, docs)
  7. Use embedding pipelines for vector search

    master

    Embedding pipelines convert text into numerical vectors. Many models require specific prefixes for queries or documents to improve performance (e.g., query: or passage: ).

    Example using sentence-transformers/multi-qa-MiniLM-L6-cos-v1 for semantic similarity:

    query = "How many people live in London?"
    docs = ["Around 9 Million people live in London", "London is known for its financial district"]
    
    model = Informers.pipeline("embedding", "sentence-transformers/multi-qa-MiniLM-L6-cos-v1")
    query_embedding = model.(query)
    doc_embeddings = model.(docs)
    
    # Manual cosine similarity calculation
    scores = doc_embeddings.map { |e| e.zip(query_embedding).sum { |d, q| d * q } }
    doc_score_pairs = docs.zip(scores).sort_by { |d, s| -s }
    query = "How many people live in London?"
    docs = ["Around 9 Million people live in London", "London is known for its financial district"]
    
    model = Informers.pipeline("embedding", "sentence-transformers/multi-qa-MiniLM-L6-cos-v1")
    query_embedding = model.(query)
    doc_embeddings = model.(docs)
    scores = doc_embeddings.map { |e| e.zip(query_embedding).sum { |d, q| d * q } }
    doc_score_pairs = docs.zip(scores).sort_by { |d, s| -s }
  8. Configure generation parameters

    master

    When calling .generate, you can pass a generation_config hash to control the output. Supported keys include:

    • max_new_tokens: Maximum number of new tokens to generate.
    • max_length: Maximum total length of the sequence.
    • num_beams: Number of beams for beam search.
    • repetition_penalty: Penalty for repeating tokens.
    • no_repeat_ngram_size: Prevents n-gram repetition.
    • bad_words_ids: List of token IDs to avoid.
    • min_length: Minimum length of the generated sequence.
    • min_new_tokens: Minimum number of new tokens to generate.
    • forced_bos_token_id: Forces a specific Beginning Of Sentence token.
    • forced_eos_token_id: Forces a specific End Of Sentence token.
    • num_return_sequences: Number of sequences to return (currently limited in implementation).
  9. Configure text generation with GenerationConfig

    master

    The Informers::Utils::GenerationConfig class is used to manage parameters for text generation. You can initialize it with a hash of configuration options. The configuration is categorized into length control, generation strategy, logit manipulation, and output variable definitions.

    Key Configuration Groups

    Length Control

    • max_length: Maximum length of the output (default: 20).
    • max_new_tokens: Maximum number of new tokens to generate.
    • min_length: Minimum length of the output (default: 0).
    • min_new_tokens: Minimum number of new tokens to generate.
    • early_stopping: Whether to stop generation early (default: false).
    • max_time: Maximum time allowed for generation.

    Generation Strategy

    • do_sample: Whether to use sampling (default: false).
    • num_beams: Number of beams for beam search (default: 1).
    • num_beam_groups: Number of beam groups (default: 1).
    • use_cache: Whether to use a cache for faster generation (default: true).

    Logit Manipulation

    • temperature: Controls randomness (default: 1.0).
    • top_k: Limits sampling to the top K tokens (default: 50).
    • top_p: Nucleus sampling parameter (default: 1.0).
    • repetition_penalty: Penalty for repeating tokens (default: 1.0).
    • no_repeat_ngram_size: Prevents repetition of n-grams (default: 0).
    • bad_words_ids: List of tokens to avoid.
    • force_words_ids: List of tokens to force.

    Output Variables

    • num_return_sequences: Number of sequences to return (default: 1).
    • output_attentions: Whether to return attention weights (default: false).
    • output_hidden_states: Whether to return hidden states (default: false).
    • output_scores: Whether to return scores (default: false).
    • return_dict_in_generate: Whether to return a dictionary (default: false).

    Special Tokens

    • pad_token_id, bos_token_id, eos_token_id.

    Usage

    Use the [] method to access values by key (converted to string) and merge! to update the configuration.

    config = Informers::Utils::GenerationConfig.new(
      "max_length" => 50,
      "do_sample" => true,
      "temperature" => 0.7,
      "top_p" => 0.9
    )
    
    # Accessing values
    max_len = config["max_length"]
    
    # Merging new config
    config.merge!("num_beams" => 5)
  10. Configure ImageFeatureExtractor via config object

    master

    The ImageFeatureExtractor (and its subclasses like CLIPFeatureExtractor, ViTFeatureExtractor, etc.) is initialized with a config hash. This hash controls the image preprocessing pipeline. Key configuration options include:

    • Normalization: image_mean (or mean), image_std (or std), and do_normalize (boolean).
    • Rescaling: do_rescale (boolean, defaults to true), rescale_factor (defaults to 1/255.0).
    • Resizing/Cropping: do_resize (boolean), do_thumbnail (boolean), size (hash with width/height), do_center_crop (boolean), crop_size (hash or integer).
    • Padding: do_pad (boolean), pad_size (hash or numeric).
    • Color/Channels: do_convert_rgb (boolean, defaults to true), do_convert_grayscale (boolean), do_flip_channel_order (boolean).
    • Other: resample (integer, 2 for bilinear), size_divisibility (or size_divisor).
  11. Configure local-only mode for model loading

    master

    To prevent the library from making network requests and force it to only use files already present in the local cache, you can use one of two methods:

    1. Per-call: Pass local_files_only: true to get_model_file or get_model_json.
    2. Globally: Set Informers.allow_remote_models = false.

    If a file is not found in the local cache while these settings are active, the library will raise an error (unless fatal: false is passed to the specific method call).