KerasHub

repository·master·Indexed 21 days ago

https://github.com/keras-team/keras-hub

A pretrained modeling library providing Keras 3 implementations of popular model architectures for text, image, and audio tasks. KerasHub allows developers to use models across JAX, TensorFlow, and PyTorch backends with a single definition. It is the renamed version of the keras-nlp package.

Tokens
15.3K
Snippets
51
Records
65
Agent score
76%

What's inside KerasHub

  1. Understand the KerasHub API design philosophy

    master

    KerasHub is designed around several core principles to ensure it serves both beginners and experts in the NLP field:

    • High-level abstraction: Even simple tasks should be packaged as one-liners to maximize ease of use.
    • Balance of ease and flexibility: Simple workflows should be easy to implement, but the library must provide a "go deeper" path for advanced users to customize components.
    • Modular building blocks: The scope includes all necessary NLP components, such as data loading, augmentation, model building, evaluation metrics, and visualization utilities.
    • Language Agnostic Design: Workflows should prioritize multi-lingual support and avoid language-specific logic (like stemming) that requires per-language rewrites.
  2. Dependency management and optional requirements in KerasHub

    master

    KerasHub aims to be self-contained, relying primarily on Keras, NumPy, TensorFlow, and Tensorflow Text. It avoids heavy external NLP dependencies like NLTK or spaCy for preprocessing.

    In cases where an external dependency is required for a specific metric or tokenizer (e.g., rouge_score), KerasHub uses an optional import pattern. If the dependency is missing, the library will raise an ImportError with specific installation instructions rather than failing at the module level.

    try:
        import rouge_score
    except ImportError:
        rouge_score = None
    
    class Rouge(keras.metrics.Metric):
        def __init__(self):
            if rouge_score is None:
                raise ImportError(
                    "ROUGE metric requires the `rouge_score` package."
                    "Please install it with `pip install rouge_score`."
                )
  3. Performance requirements for KerasHub components

    master

    To ensure high performance and efficiency, KerasHub components (layers, metrics, and tokenizers) follow these computational guidelines:

    • TensorFlow Graph Compatibility: All components should be compatible with @tf.function. They should rely on tf.strings and tf.text operations to ensure string manipulation happens within the TensorFlow graph.
    • XLA Compilation: Trainable modeling components should be designed to be XLA compilable (e.g., compatible with tf.function(jit_compile=True)) to leverage significant performance gains.
    • tf.data Integration: Preprocessing tools must be runnable inside a tf.data pipeline. Augmentations should be dynamic (performed on-the-fly during training) rather than precomputed. Preprocessing layers should support both batched and unbatched data inputs.
  4. Naming conventions for Layers and Models

    master

    When naming layers and models, follow these rules:

    • Acronyms: Capitalize all acronyms (e.g., LSTM, KLDivergence, GPT2, XLMRoberta).
    • Pronounceable Acronyms: If an abbreviation is common and pronounceable, treat it as a standalone word (e.g., Bert, Deberta).
    • File Names: Use snake_case. Treat acronyms as a single segment. For example, XLMRoberta should be in a file named xlm_roberta.py.
    • Public Classes: Ideally, keep publicly documented classes in their own files, matching the class name to the filename (e.g., BertClassifier in bert_classifier.py).
  5. Install KerasHub

    master

    To install the latest stable release of KerasHub with Keras 3, use pip. Note that installing KerasHub will automatically pull in TensorFlow to support the tf.data API for preprocessing, though training can still be performed on other backends like JAX or PyTorch.

    To install the latest nightly builds for both KerasHub and Keras, use the nightly package.

    # Install latest stable release
    pip install --upgrade keras-hub
    
    # Install latest nightly changes
    pip install --upgrade keras-hub-nightly
  6. Requirements for adding task models and preprocessors

    master

    This optional stage extends the model to specific downstream tasks (e.g., Masked LM, Classification). The following files and verification steps are required:

    • xx/xx_<task>.py: The task model implementation (e.g., a classifier head).
    • xx/xx_<task>_preprocessor.py: The preprocessor that prepares inputs suitable for the task model.
    • xx/xx_<task>_test.py and xx/xx_<task>_preprocessor_test.py: Unit tests for both the task model and the preprocessor.
    • Verification: A Colab notebook link must be included in the PR description. This notebook must demonstrate that the output of your preprocessor matches the output of the original preprocessor.
  7. Train WordPiece vocabularies on Wikipedia

    master

    This guide outlines the process for training WordPiece vocabularies using Wikipedia dumps.

    Warning: This is unmaintained helper code. It is highly recommended to run these scripts on Google Cloud Storage (GCS). Because these processes are long-running, use a terminal multiplexer like screen or tmux when running commands remotely to prevent the scripts from being killed if your connection drops.

    Workflow Overview

    1. Download and Extract: For every Wikipedia dump you wish to include, you must perform steps 1 and 2.
    2. Configure Cleaning: After downloading all data, update the list of directory names in word_piece_cleaning_script.py to match your downloaded folders.
    3. Train: Update the list in word_piece_training_script.py to match your directories and execute the training script.
    ### Summary of Commands
    
    #### 1. Download Wikipedia Dataset
    Use `curl` to download the specific Wikipedia dump (e.g., Portuguese Wikipedia):
    ```bash
    curl -O https://dumps.wikimedia.org/ptwiki/20220801/ptwiki-20220801-pages-articles-multistream.xml.bz2

    2. Run Wikipedia Dataset Extractor

    Extract the downloaded .xml.bz2 file using wikiextractor:

    python3 -m wikiextractor.WikiExtractor arwiki-20220802-pages-articles-multistream.xml.bz2

    3. Additional Removals

    Run the cleaning script to perform additional text removals:

    python3 word_piece_cleaning_script.py

    4. Run Train Vocabulary

    Run the training script to generate the vocabularies:

    python3 word_piece_training_script.py
  8. Migrate from KerasNLP to KerasHub

    master
    The keras-nlp package has been renamed to keras-hub. While a shim package exists to maintain backward compatibility for pip install keras-nlp and import keras_nlp, users should transition to using keras-hub for all new development and to access the latest multi-framework NLP models and features.
  9. Implement a model backbone class

    master

    When contributing a new model, the first major step is implementing the backbone class. KerasHub follows a pattern of wrapping Keras' functional style models within a class.

    Key Implementation Details:

    • Inputs: Standard text model inputs typically include token_ids (integer representations) and padding_mask.
    • Architecture Components: Use standard layers where possible:
      • Embedding: keras.layers.Embedding, keras_hub.layers.PositionEmbedding, or keras_hub.layers.TokenAndPositionEmbedding.
      • Encoder: keras_hub.layers.TransformerEncoder or keras_hub.layers.FNetEncoder.
      • Decoder: keras_hub.layers.TransformerDecoder.
      • Other: keras.layers.LayerNorm, keras.layers.Dropout, keras.layers.Conv1D.
    • Custom Layers: If the model uses a paradigm shift (like relative attention), you must implement custom layers from scratch. For minor tweaks (e.g., removing a bias term), you can inherit from standard layers and modify them.
    • Note: Do not include the from_presets() function in the initial backbone PR; this is added during the presets stage.

    Validation Requirements:

    • Weight Conversion: You must verify that your implementation matches the original source. It is recommended to provide a Colab link in your PR that converts original weights to the KerasHub format and compares outputs.
    • Unit Tests: Implement tests to ensure the forward pass works and the model can be saved and loaded correctly.
    # Example reference: keras_hub.layers.DistilBertBackbone
    # Use Keras functional API wrapped in a class
  10. Benchmark sentiment analysis models

    master

    To benchmark classification models like sentiment analysis, run the sentiment_analysis.py script from the root of the repository.

    CLI Flags

    • --model: (Required) Specifies the model name.
    • --preset: Specifies the preset under testing. This can be set to None.
    • --learning_rate: Common training flag for the learning rate.
    • --num_epochs: Common training flag for the number of training epochs.
    • --batch_size: Common training flag for the batch size.
    • --mixed_precision_policy: Common training flag for the mixed precision policy (e.g., mixed_float16).

    Output

    The script outputs the validation accuracy for each epoch, the testing accuracy after training is complete, and the total elapsed time in seconds.

    python3 keras_hub/benchmarks/sentiment_analysis.py \
        --model="BertTextClassifier" \
        --preset="bert_small_en_uncased" \
        --learning_rate=5e-5 \
        --num_epochs=5 \
        --batch_size=32 \
        --mixed_precision_policy="mixed_float16"
  11. Implement a model tokenizer

    master

    The second step in model contribution is adding the tokenizer. Most text models use subword tokenizers (WordPiece, SentencePiece, BPE).

    Implementation Steps:

    1. Inheritance: Inherit from an existing KerasHub base tokenizer class (e.g., keras_hub.tokenizers.WordPieceTokenizer).
    2. Special Tokens: You must add special tokens (e.g., beginning-of-sequence, end-of-sequence, mask, pad) as member attributes to the tokenizer class. These attributes are used by preprocessor layers.
    3. Unit Tests: Create tests using a dummy vocabulary to verify tokenization and detokenization processes.
    # Example pattern
    class MyModelTokenizer(keras_hub.tokenizers.WordPieceTokenizer):
        def __init__(self, ...):
            super().__init__(...)
            self.cls_token = '...' # Special tokens as member attributes
            self.sep_token = '...'
  12. Requirements for adding a model backbone

    master

    To contribute the first PR for a new model, you must implement the backbone architecture. The following files and verification steps are required:

    • xx/xx_backbone.py: Contains the model graph implementation.
    • xx/xx_backbone_test.py: Contains unit tests for the backbone.
    • Verification: A Colab notebook link must be included in the PR description. This notebook must demonstrate that the outputs of your implemented backbone match the outputs of the original source model.