Using Class UDFs to Process Data
Class UDFs are implemented based on the object-oriented programming paradigm, making them suitable processing logic that requires initialization parameters, resource loading, or stateful operations. The __init__ method is used to initialize resources (such as loading a model), the __call__ method is used to perform calculations on each row of data, and the __del__ method can be used to clean up resources as needed.
Scenario
In a text processing scenario, a SentencePiece tokenization model is required to perform subword tokenization on the text column content of the text_samples table. The model file needs to be loaded at once during UDF initialization and then reused for each row of text. By using a class UDF, the spiece.model file can be loaded and EOS encoding options configured in __init__. The __call__ method then performs tokenization on each row of text and returns the tokenization results in JSON format, avoiding the overhead of loading the model repeatedly for each row.
Notes and Constraints
- The class must define an __init__ method, and its parameter names must match the parameter names used during call.
- The class must define a __call__ member method, which serves as the main entry point of the UDF.
- The class can optionally define a __del__ member method, which does not support passing parameters.
- When a class UDF is called, only constant values can be passed to the __init__ method—data columns or other expressions are unsupported.
Prerequisites
- A table has been created and data has been written to it. For details, see Creating a Table and Writing Data to the Table.
- The Python 3.11 has been installed.
Preparations
This example uses the SentencePiece tokenization model, so the model file spiece.model must be prepared. It is recommended to obtain the SentencePiece tokenizer included with the T5 model from Hugging Face. The acquisition method is as follows:
- Install the SentencePiece dependency.
pip install sentencepiece==0.2.0
- Install the Hugging Face command line tool.
pip install huggingface-hub
- Download the model file to the same directory as the sample script.
hf download google-t5/t5-small spiece.model --local-dir .
If the hf download command is unavailable, manually download the file using a browser.
- Search for google-t5/t5-small on the Hugging Face website and go to the model homepage.
- Click the Files and versions tab.
- Locate the spiece.model file and click the file name to go to its details page.
- Click the download button in the upper right corner of the file content to save the file to the local PC.
- Place the downloaded spiece.model file in the same directory as the example script.
Example
This example defines a class UDF based on the SentencePiece tokenization model. It loads the model file in __init__ and performs subword tokenization on each row of text in __call__. After registering it in the database, it processes the text column of the text_samples table using the map method.
- Define the class UDF class SPManager, which loads the SentencePiece model file in __init__, and performs tokenization on the text in __call__, returning JSON-formatted results.
- Connect to the AuraJobV2 endpoint and set the UDF workspace.
- Delete the existing UDF with the same name (repeated execution is supported).
- Register the class UDF to the target database, specifying dependency packages and model files.
- Obtain the registered UDF operator and load the text_samples dataset.
- Call the UDF via the map method to tokenize the content column, generating the pieces_column column.
- Select the content and pieces_column columns, execute the query, and print the results.
- Disable the AuraJobV2 endpoint connection.
import os from aura_frame.multimodal import ai_lake from sentencepiece import SentencePieceProcessor target_database = "test" #Create a database in LakeFormation, for example, test. For details, see Creating a DataArts Lake Formation Instance and Planning Metadata. #Connect to the AuraJobV2 endpoint. For details about the parameters, see Establishing a Connection with the AuraJobV2 Endpoint. con = ai_lake.connect( aura_endpoint=os.getenv("aura_endpoint"), # Endpoint where the AuraJobV2 endpoint is located aura_endpoint_id=os.getenv("aura_endpoint_id"), # AuraJobV2 endpoint ID aura_endpoint_name=os.getenv("aura_endpoint_name"),# AuraJobV2 endpoint name aura_workspace_id=os.getenv("aura_workspace_id"), # Workspace ID lf_catalog_name=os.getenv("lf_catalog_name"), # LakeFormation Catalog name access_key=os.getenv("access_key"), # Access Key ID (AK) secret_key=os.getenv("secret_key"), # Secret Key (SK) default_database=target_database, # LakeFormation database name use_single_cn_mode=True, # Whether to enable the single-CN mode logging_level=logging.INFO # Set the log level. ) #Configure the UDF deployment workspace. For details about the parameters, see Configuring the UDF Deployment Workspace. con.set_function_staging_workspace( obs_directory_base=os.getenv("obs_directory_base"), # Path for storing UDFs in the parallel file system. obs_bucket_name=os.getenv("obs_bucket_name"), # Name of the parallel file system. obs_server=os.getenv("obs_server"), # OBS endpoint access_key=os.getenv("access_key"), # Access Key ID (AK) secret_key=os.getenv("secret_key"), # Secret Key (SK) ) class SPManager: def __init__(self, model_file: str, *, bos: bool = False, eos: bool = False, reverse: bool = False) -> None: sp = SentencePieceProcessor(model_file=model_file) opts = ":".join(opt for opt, flag in (("bos", bos), ("eos", eos), ("reverse", reverse)) if flag) sp.set_encode_extra_options(opts) self.spm = sp def __call__(self, input_text: str) -> str: import json return json.dumps(self.spm.encode(input_text, out_type=str)) try: # Delete the existing UDF with the same name (repeated execution is supported). con.delete_function("SPManager", database=target_database, if_it_exists=True) # Register the class UDF. con.create_scalar_function( SPManager, database=target_database, packages=["sentencepiece==0.2.0"], imports=["spiece.model"], ) # Obtain the UDF operator and use it in DataFrame. udf = con.get_function("SPManager", database=target_database) ds = con.load_dataset("text_samples", database=target_database) ds = ds.map( fn=udf, on=[ds.content], as_col="pieces_column", model_file="spiece.model", eos=True, ) ds = ds.select_columns(ds.content, ds.pieces_column) df = ds.execute() print(df) finally: con.close()
Helpful Links
What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot