### StartEndPacker Usage Examples Source: https://keras.io/keras_hub/api/preprocessing_layers/start_end_packer Examples demonstrating the use of StartEndPacker with various input types including unbatched/batched integers and strings, as well as multiple start tokens. ```python >>> inputs = [5, 6, 7] >>> start_end_packer = keras_hub.layers.StartEndPacker( ... sequence_length=7, start_value=1, end_value=2, ... ) >>> outputs = start_end_packer(inputs) >>> np.array(outputs) array([1, 5, 6, 7, 2, 0, 0], dtype=int32) ``` ```python >>> inputs = [[5, 6, 7], [8, 9, 10, 11, 12, 13, 14]] >>> start_end_packer = keras_hub.layers.StartEndPacker( ... sequence_length=6, start_value=1, end_value=2, ... ) >>> outputs = start_end_packer(inputs) >>> np.array(outputs) array([[ 1, 5, 6, 7, 2, 0], [ 1, 8, 9, 10, 11, 2]], dtype=int32) ``` ```python >>> inputs = tf.constant(["this", "is", "fun"]) >>> start_end_packer = keras_hub.layers.StartEndPacker( ... sequence_length=6, start_value="", end_value="", ... pad_value="" ... ) >>> outputs = start_end_packer(inputs) >>> np.array(outputs).astype("U") array(['', 'this', 'is', 'fun', '', ''], dtype='>> inputs = tf.ragged.constant([["this", "is", "fun"], ["awesome"]]) >>> start_end_packer = keras_hub.layers.StartEndPacker( ... sequence_length=6, start_value="", end_value="", ... pad_value="" ... ) >>> outputs = start_end_packer(inputs) >>> np.array(outputs).astype("U") array([['', 'this', 'is', 'fun', '', ''], ['', 'awesome', '', '', '', '']], dtype='>> inputs = tf.ragged.constant([["this", "is", "fun"], ["awesome"]]) >>> start_end_packer = keras_hub.layers.StartEndPacker( ... sequence_length=6, start_value=["", ""], end_value="", ... pad_value="" ... ) >>> outputs = start_end_packer(inputs) >>> np.array(outputs).astype("U") array([['', '', 'this', 'is', 'fun', ''], ['', '', 'awesome', '', '', '']], dtype='": 0, "": 1, "": 2, "": 3} vocab = {**vocab, "a": 4, "Ġquick": 5, "Ġfox": 6} merges = ["Ġ q", "u i", "c k", "ui ck", "Ġq uick"] merges += ["Ġ f", "o x", "Ġf ox"] tokenizer = keras_hub.models.BartTokenizer( vocabulary=vocab, merges=merges, ) tokenizer("The quick brown fox jumped.") ``` -------------------------------- ### T5GemmaSeq2SeqLMPreprocessor Usage Examples Source: https://keras.io/keras_hub/api/models/t5gemma/t5gemma_seq_2_seq_lm_preprocessor Demonstrates loading from a preset, processing input strings and dictionaries, mapping over tf.data.Dataset, and handling generation preprocessing and postprocessing. ```python import tensorflow as tf import numpy as np # Load the preprocessor from a preset. preprocessor = keras_hub.models.T5GemmaSeq2SeqLMPreprocessor.from_preset( "t5gemma_b_b_prefixlm_it" ) # For example usage, see the dictionary example below which provides # both encoder and decoder text. # Tokenize a batch of sentences. preprocessor(["The quick brown fox jumped.", "Call me Ishmael."]) # Tokenize a dictionary with separate encoder and decoder inputs. preprocessor({ "encoder_text": "The quick brown fox jumped.", "decoder_text": "The fast fox." }) # Apply tokenization to a [`tf.data.Dataset`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset). encoder_features = tf.constant(["The quick brown fox.", "Call me Ishmael."]) decoder_features = tf.constant(["The fast fox.", "I am Ishmael."]) ds = tf.data.Dataset.from_tensor_slices( {"encoder_text": encoder_features, "decoder_text": decoder_features} ) ds = ds.map(preprocessor, num_parallel_calls=tf.data.AUTOTUNE) # Prepare tokens for generation. preprocessor.generate_preprocess({ "encoder_text": "The quick brown fox jumped.", "decoder_text": "The fast fox." }) # Map generation outputs back to strings. preprocessor.generate_postprocess({ 'decoder_token_ids': np.array([[2, 714, 4320, 8426, 25341, 1, 0, 0]]), 'decoder_padding_mask': np.array([[1, 1, 1, 1, 1, 1, 0, 0]]), }) ``` -------------------------------- ### Install Keras-Hub and Keras Source: https://keras.io/keras_hub/getting_started Install the keras-hub and keras libraries using pip. Ensure you have the latest versions for optimal performance. ```bash !pip install --upgrade --quiet keras-hub keras ``` -------------------------------- ### Install KerasHub and related libraries Source: https://keras.io/keras_hub/guides/upload Installs the necessary libraries for using KerasHub, Hugging Face Hub, and Kaggle Hub. ```bash !pip install -q --upgrade keras-hub huggingface-hub kagglehub ``` -------------------------------- ### Usage Examples for SmolLM3Backbone Source: https://keras.io/keras_hub/api/models/smollm3/smollm3_backbone Demonstrates loading a pre-trained model from a preset and initializing a custom model from scratch. ```python input_data = { "token_ids": np.ones(shape=(1, 12), dtype="int32"), "padding_mask": np.array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]]), } # Pretrained SmolLM3 decoder. model = keras_hub.models.SmolLM3Backbone.from_preset( "hf://HuggingFaceTB/SmolLM3-3B" ) model(input_data) # Randomly initialized SmolLM3 decoder with custom config. model = keras_hub.models.SmolLM3Backbone( vocabulary_size=49152, hidden_dim=576, intermediate_dim=1536, num_layers=30, num_attention_heads=9, num_key_value_heads=3, attention_bias=False, attention_dropout=0.0, rope_layer_enabled_list=[True] * 30, layer_types=["attention"] * 30, mlp_bias=False, layer_norm_epsilon=1e-5, max_position_embeddings=2048, rope_theta=10000.0, partial_rotary_factor=1.0, ) model(input_data) ``` -------------------------------- ### Initialize and use DFineBackbone Source: https://keras.io/keras_hub/api/models/d_fine/d_fine_backbone Demonstrates basic model initialization without denoising and advanced initialization with contrastive denoising training. ```python import keras import numpy as np from keras_hub.models import DFineBackbone from keras_hub.models import HGNetV2Backbone # Example 1: Basic usage without denoising. # First, build the `HGNetV2Backbone` instance. hgnetv2 = HGNetV2Backbone( stem_channels=[3, 16, 16], stackwise_stage_filters=[ [16, 16, 64, 1, 3, 3], [64, 32, 256, 1, 3, 3], [256, 64, 512, 2, 3, 5], [512, 128, 1024, 1, 3, 5], ], apply_downsample=[False, True, True, True], use_lightweight_conv_block=[False, False, True, True], depths=[1, 1, 2, 1], hidden_sizes=[64, 256, 512, 1024], embedding_size=16, use_learnable_affine_block=True, hidden_act="relu", image_shape=(None, None, 3), out_features=["stage3", "stage4"], data_format="channels_last", ) # Then, pass the backbone instance to `DFineBackbone`. backbone = DFineBackbone( backbone=hgnetv2, decoder_in_channels=[128, 128], encoder_hidden_dim=128, num_denoising=0, # Disable denoising num_labels=80, hidden_dim=128, learn_initial_query=False, num_queries=300, anchor_image_size=(256, 256), feat_strides=[16, 32], num_feature_levels=2, encoder_in_channels=[512, 1024], encode_proj_layers=[1], num_attention_heads=8, encoder_ffn_dim=512, num_encoder_layers=1, hidden_expansion=0.34, depth_multiplier=0.5, eval_idx=-1, num_decoder_layers=3, decoder_attention_heads=8, decoder_ffn_dim=512, decoder_n_points=[6, 6], lqe_hidden_dim=64, num_lqe_layers=2, out_features=["stage3", "stage4"], image_shape=(None, None, 3), data_format="channels_last", seed=0, ) # Prepare input data. input_data = keras.random.uniform((2, 256, 256, 3)) # Forward pass. outputs = backbone(input_data) # Example 2: With contrastive denoising training. labels = [ { "boxes": np.array([[0.5, 0.5, 0.2, 0.2], [0.4, 0.4, 0.1, 0.1]]), "labels": np.array([1, 10]), }, { "boxes": np.array([[0.6, 0.6, 0.3, 0.3]]), "labels": np.array([20]), }, ] # Pass the `HGNetV2Backbone` instance to `DFineBackbone`. backbone_with_denoising = DFineBackbone( backbone=hgnetv2, decoder_in_channels=[128, 128], encoder_hidden_dim=128, num_denoising=100, # Enable denoising num_labels=80, hidden_dim=128, learn_initial_query=False, num_queries=300, anchor_image_size=(256, 256), feat_strides=[16, 32], num_feature_levels=2, encoder_in_channels=[512, 1024], encode_proj_layers=[1], num_attention_heads=8, encoder_ffn_dim=512, num_encoder_layers=1, hidden_expansion=0.34, depth_multiplier=0.5, eval_idx=-1, num_decoder_layers=3, decoder_attention_heads=8, decoder_ffn_dim=512, decoder_n_points=[6, 6], lqe_hidden_dim=64, num_lqe_layers=2, out_features=["stage3", "stage4"], image_shape=(None, None, 3), seed=0, labels=labels, ) # Forward pass with denoising. outputs_with_denoising = backbone_with_denoising(input_data) ``` -------------------------------- ### RobertaTextClassifier Examples Source: https://keras.io/keras_hub/api/models/roberta/roberta_text_classifier Examples demonstrating how to use the RobertaTextClassifier with raw string data, preprocessed integer data, and custom backbones. ```APIDOC ### Examples Raw string data. ```python features = ["The quick brown fox jumped.", "I forgot my homework."] labels = [0, 3] # Pretrained classifier. classifier = keras_hub.models.RobertaTextClassifier.from_preset( "roberta_base_en", num_classes=4, ) classifier.fit(x=features, y=labels, batch_size=2) classifier.predict(x=features, batch_size=2) # Re-compile (e.g., with a new learning rate). classifier.compile( loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer=keras.optimizers.Adam(5e-5), jit_compile=True, ) # Access backbone programmatically (e.g., to change `trainable`). classifier.backbone.trainable = False # Fit again. classifier.fit(x=features, y=labels, batch_size=2) ``` Preprocessed integer data. ```python features = { "token_ids": np.ones(shape=(2, 12), dtype="int32"), "padding_mask": np.array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]] * 2), } labels = [0, 3] # Pretrained classifier without preprocessing. classifier = keras_hub.models.RobertaTextClassifier.from_preset( "roberta_base_en", num_classes=4, preprocessor=None, ) classifier.fit(x=features, y=labels, batch_size=2) ``` Custom backbone and vocabulary. ```python features = ["a quick fox", "a fox quick"] labels = [0, 3] vocab = {"": 0, "": 1, "": 2, "": 3} vocab = {**vocab, "a": 4, "Ġquick": 5, "Ġfox": 6} merges = ["Ġ q", "u i", "c k", "ui ck", "Ġq uick"] merges += ["Ġ f", "o x", "Ġf ox"] tokenizer = keras_hub.models.RobertaTokenizer( vocabulary=vocab, merges=merges ) preprocessor = keras_hub.models.RobertaTextClassifierPreprocessor( tokenizer=tokenizer, sequence_length=128, ) backbone = keras_hub.models.RobertaBackbone( vocabulary_size=20, num_layers=4, num_heads=4, hidden_dim=256, intermediate_dim=512, max_sequence_length=128 ) classifier = keras_hub.models.RobertaTextClassifier( backbone=backbone, preprocessor=preprocessor, num_classes=4, ) classifier.fit(x=features, y=labels, batch_size=2) ``` ``` -------------------------------- ### Initialize and run MoonshineBackbone Source: https://keras.io/keras_hub/api/models/moonshine/moonshine_backbone Demonstrates how to instantiate the MoonshineBackbone with custom parameters and perform a forward pass using dummy audio and token data. ```python import numpy as np import keras from keras_hub.models import MoonshineBackbone # Create random input data for demonstration. # Input is now raw-ish audio features (e.g., from MoonshineAudioConverter). encoder_raw_input_values = np.random.rand(1, 16000, 1).astype("float32") # Mask corresponding to the raw input time dimension encoder_padding_mask = np.ones((1, 16000), dtype="bool") decoder_token_ids = np.random.randint( 0, 1000, size=(1, 20), dtype="int32" ) decoder_padding_mask = np.ones((1, 20), dtype="bool") # Initialize the Moonshine backbone with specific parameters. backbone = MoonshineBackbone( vocabulary_size=10000, filter_dim=256, encoder_num_layers=6, decoder_num_layers=6, hidden_dim=256, intermediate_dim=512, encoder_num_heads=8, decoder_num_heads=8, feedforward_expansion_factor=4, decoder_use_swiglu_activation=True, encoder_use_swiglu_activation=False, ) # Forward pass through the model. outputs = backbone( { "encoder_input_values": encoder_raw_input_values, "encoder_padding_mask": encoder_padding_mask, "decoder_token_ids": decoder_token_ids, "decoder_padding_mask": decoder_padding_mask, } ) ```