MaxFrame AI Function

更新时间:
复制 MD 格式

This document describes how to use the MaxFrame AI Function in Alibaba Cloud MaxCompute and provides use cases for large language model (LLM) offline inference.

Overview

MaxFrame AI Function is an end-to-end solution within the Alibaba Cloud MaxCompute platform for large language model (LLM) offline inference. It seamlessly integrates data processing with AI capabilities, lowering the barrier to enterprise-level LLM adoption.

  • Design philosophy: "Data in, results out." This philosophy lets you use the MaxFrame Python development framework and pandas-style APIs to handle the entire workflow—from data preparation and processing to model inference and result storage—within the MaxCompute ecosystem.

  • Use cases: MaxFrame AI Function is ideal for processing massive volumes of structured data, such as log analysis and user behavior logs, and unstructured data, such as text translation and document summarization. It also supports data embedding and other scenarios. It can process petabyte-scale data in a single job and achieves low latency and linear scalability through its distributed architecture. You can use it to extract structured information from text, summarize content, generate abstracts, translate languages, and perform tasks like text quality assessment and sentiment classification. This simplifies LLM data processing and improves result quality.

  • Architecture

    MaxFrame AI Function provides a flexible, general-purposegenerate interface and concise, scenario-basedtask interfaces (such as text translation, structured extraction, and embedding). You can select a model and provide a MaxCompute table and prompts as input.

    When you call an interface, MaxFrame first performs data sharding on the table. You can set an appropriate concurrency level based on the data size and start a group of workers to run the task. Each worker uses your prompt template to render prompts from the input data rows and runs model inference. The process then writes the results, including the success status, back to a MaxCompute table.

    The following figure shows the overall architecture and workflow:

    image.png

  • Key advantages:

    • Ease of use: Familiar Python APIs, an out-of-the-box model library, and zero deployment cost.

    • Scalability: Leverages MaxCompute CU (Compute Unit), GU (GPU Unit), and Inference Quota resources for large-scale parallel processing and high token throughput.

    • Data + AI integration: A unified platform for data reading, processing, AI inference, and result storage. This reduces data migration costs and improves development efficiency.

    • Broad scenario coverage: Covers more than 10 common scenarios, including translation, structured extraction, and vectorization.

Requirements

  • Supported regions:

    China (Hangzhou), China (Shanghai), China (Beijing), China (Ulanqab), China (Shenzhen), China (Chengdu), China (Hong Kong), China (Hangzhou) Finance Cloud, and China (Shanghai) Finance Cloud.

  • Supported Python version: Python 3.11.

  • Supported SDK version: Requires MaxFrame SDK version 2.7.1 or later. You can check the version by running the following command:

    // For Windows
    pip list | findstr maxframe
    
    // For Linux
    pip list | grep maxframe

    If your version is outdated, runpip install --upgrade maxframe to install the latest version.

  • Install the latest MaxFrame client.

Supported models

MaxFrame provides out-of-the-box support for several built-in LLMs, such asQwen 3,Deepseek-R1-Distill-Qwen, andQwen3-embedding. It also supports calling commercial large models from Model Studio (Bailian), such as the multimodal and text-based flagship modelsqwen3.7-max,qwen3.6-plus,qwen3.6-flash,deepseek-v4-pro,deepseek-v4-flash,qwen3-vl-embedding, andtext-embedding-v4. All models are hosted offline within the MaxCompute platform, eliminating the need to manage model downloads, distribution, or API call concurrency limits. You can use the models through simple API calls, leveraging the massive computing resources of MaxCompute to complete large language model (LLM) offline inference tasks with high overall token throughput and concurrency.

Supported models

Model type

Model name

Applicable quota

Model Studio (Bailian) commercial flagship large models

  • qwen3.7-plus

  • qwen3.7-max

  • qwen3.6-plus

  • qwen3.6-flash

  • qwen3-asr-flash

  • deepseek-v4-pro

  • deepseek-v4-flash

  • qwen3-vl-embedding

  • text-embedding-v4

  • qwen3.5-397b-a17b

  • Inference Quota resources (token-based billing)

Qwen 3 series open-source models

  • Qwen3-0.6B

  • Qwen3-1.7B

  • Qwen3-4B

  • Qwen3-8B

  • Qwen3-14B

  • pay-as-you-go standard computing resources (CU)

  • subscription standard computing resources (CU)

  • subscription AI computing resources (GU)

Qwen Embedding open-source models

  • Qwen3-Embedding-8B

  • subscription standard computing resources (GU)

Deepseek-R1-Distill-Qwen series open-source models

  • DeepSeek-R1-Distill-Qwen-1.5B

  • DeepSeek-R1-Distill-Qwen-7B

  • DeepSeek-R1-Distill-Qwen-14B

  • pay-as-you-go standard computing resources (CU)

  • subscription standard computing resources (CU)

Deepseek-R1-0528-Qwen3 open-source model

  • DeepSeek-R1-0528-Qwen3-8B

  • pay-as-you-go standard computing resources (CU)

  • subscription standard computing resources (CU)

Quota resource types

MaxFrame supports three types of resources, allowing you to choose the best fit for your model size and business needs.

CU Quota resources

A CU (Compute Unit) (1 CU = 1 CPU + 4 GB memory) provides general-purpose CPU computing resources and is suitable for small models and data volumes.

Configuration:

# Use CU Quota computing resources
options.session.quota_name = "mf_cpu_quota"

GU Quota resources

A GU (GPU Unit) provides GPU computing resources optimized for large model inference. It supports larger model sizes and is suitable for models of 8B parameters or more.

Configuration:

# Use GU Quota computing resources
options.session.gu_quota_name = "mf_gpu_quota"

Inference Quota resources (token-based billing)

This option lets you call commercial large models from Model Studio (Bailian), such asqwen3-max andtext-embedding-v4, for large-scale model inference tasks. You are billed based on token consumption. This approach eliminates the need to provision CU or GU resources or manage the underlying computing resources, providing a flexible, convenient, and cost-effective solution.

API reference

MaxFrame AI Function provides a general-purposegenerate interface and scenario-based Task interfaces to balance flexibility with ease of use.

General API:generate

General API: generate

Key parameters

Parameter

Required

Description

model_name

Yes

The name of the model to use.

df

Yes

The input DataFrame containing the text or data for analysis.

prompt_template

Yes

A list of messages compatible with the OpenAI chat message format. You can usef-string syntax in the content to reference columns from the DataFrame.

Task APIs:Task

Task APIs: Task

Preset, standardized task interfaces simplify development for common scenarios. Currently supportedtask interfaces includetranslate,extract, andembed.

  • Key parameters

    Parameter

    Required

    Description

    model_name

    Yes

    The name of the model to use.

    df

    Yes

    The input DataFrame containing the text or data for analysis.

    task interface

    Yes

    • translate: text translation

    • extract: structured data extraction

    • embed: vectorization

  • Usage example

    from maxframe.learn.contrib.llm.models.managed import ManagedTextLLM
    
    llm = ManagedTextLLM(name="<model_name>")
    
    # Text translation
    translated_df = llm.translate(
        df["english_column"],
        source_language="english",
        target_language="Chinese",
        examples=[("Hello", "你好"), ("Goodbye", "再见")],
    )
    
    translated_df.execute()

Use cases

GU Quota scenarios

GU Quota scenarios

Language translation

Scenario: A multinational corporation needs to translate 100,000 English contracts into Chinese and annotate key clauses.

import os
import maxframe.dataframe as md
from maxframe import new_session
from maxframe.config import options
from maxframe.udf import with_running_options
from odps import ODPS

options.dag.settings = {
    "engine_order": ["DPE", "MCSQL"]
}

o = ODPS(
    os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    project='your-default-project',
    endpoint='your-end-point',
)

# Initialize a MaxFrame session
session = new_session(o)

# Print the Logview URL for the job
print(session.get_logview_address())

# 1. Use GU Quota computing resources
options.session.gu_quota_name = "mf_gu_quota"

# 2. Use the Qwen3-1.7B model
from maxframe.learn.contrib.llm.models.managed import ManagedTextLLM

llm = ManagedTextLLM(name="Qwen3-1.7B")

# 3. Prepare the data. You can skip this step if you already have data.
# o.execute_sql("""
#   CREATE TABLE IF NOT EXISTS raw_contracts (
#       en STRING
#   );
#   """)
# 
# o.execute_sql("""
#   INSERT INTO raw_contracts VALUES
#   ('This agreement is governed by the laws of the State of California.'),
#   ('The tenant shall pay rent on the first day of each month.'),
#   ('Either party may terminate this contract with 30 days written notice.'),
#   ('All intellectual property rights shall remain with the original owner.'),
#   ('The warranty period for this product is twelve months from the date of purchase.');
#   """)

df = md.read_odps_table("raw_contracts")

# 4. Define the prompt template
messages = [
    {
        "role": "system",
        "content": "You are a document translation expert who can fluently translate the user's English text into Chinese.",
    },
    {
        "role": "user",
        "content": "Please translate the following English text into Chinese. Output only the translated text, with no other content.\n\n Example:\nInput: Hi\nOutput: 你好。\n\n Text to translate:\n\n{en}",
    },
]

# 5. Call the `generate` interface, define the prompt, and reference the data column.
result_df = llm.generate(
    df,
    prompt_template=messages,
    params={
        "temperature": 0.7,
        "top_p": 0.8,
    },
).execute()

# 6. Write the results to a MaxCompute table
result_df.to_odps_table("raw_contracts_result")

Keyword extraction

Scenario: This example demonstrates how MaxFrame AI Function can process unstructured data, such as text and images, which often pose challenges for big data analytics.

This code extracts a candidate's work experience from resumes, using randomly generated text as input. For detailed development practices, see AI Function on GU Development Practices.

import maxframe.dataframe as md
from maxframe import new_session
from maxframe.config import options
from maxframe.udf import with_running_options
from odps import ODPS

options.dag.settings = {
    "engine_order": ["DPE", "MCSQL"]
}

o = ODPS(
    os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    project='your-default-project',
    endpoint='your-end-point',
)

# Initialize a MaxFrame session
session = new_session(o)

# Print the Logview URL for the job
print(session.get_logview_address())

# 1. Use GU Quota computing resources
options.session.gu_quota_name = "mf_gu_quota"

# 2. Use the Qwen3 4B model
from maxframe.learn.contrib.llm.models.managed import ManagedTextLLM

llm = ManagedTextLLM(name="Qwen3-4B-Instruct-2507-FP8")

df = md.read_odps_table("traditional_chinese_medicine", index_col="index")

# Specify four concurrent partitions
parallel_partitions = 4
df = df.mf.rebalance(num_partitions=parallel_partitions)

# 3. Use the preset `extract` task interface
result_df = llm.extract(
    df["text"],
    description="Please extract structured data from the following medical record in order. Return the final output in strict JSON format according to the schema.",
    schema=MedicalRecord,
    examples=[(example_input, example_output)],
)
result_df.execute()

Inference Quota scenarios

Inference Quota scenarios

Text vectorization

Scenario description: This scenario involves using the Bailian commercial model text-embedding-v4 for vectorization tasks. You are billed by token usage and do not need to manage underlying computing resources. This approach is suitable for complex text analysis, tasks requiring large models, or high-quality inference using Bailian's commercial large models.

Sample code

import os
import maxframe.dataframe as md
from maxframe import new_session
from maxframe.config import options
from maxframe.udf import with_running_options
from odps import ODPS

options.dag.settings = {
    "engine_order": ["DPE", "MCSQL"]
}

o = ODPS(
    os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    project='your-default-project',
    endpoint='your-end-point',
)

# Initialize a MaxFrame session
session = new_session(o)

# Print the Logview URL for the job
print(session.get_logview_address())

# 1. Create a text-embedding-v4 model instance (using Inference Quota)
# Load the text-embedding-v4 model from the Model Studio (Bailian) public model set
from maxframe.learn.utils import read_odps_model

llm = read_odps_model("text-embedding-v4", project="bigdata_public_modelset")

# 2. Read the data
df = md.read_odps_table("user_feedback_table")

# 3. Perform vectorization
result_df = llm.embed(
    df["query"],
    running_options={"max_tokens": 1024, "verbose": True},
    simple=True,
).execute()

# 4. Write the result to a MaxCompute table
result_df.to_odps_table("feedback_analysis_result")

Image understanding

Scenario: Use a commercial multimodal model from Model Studio (Bailian) for tasks requiring high-quality inference on data like images and text. On-demand resource consumption makes this approach cost-effective.

Sample code

import os

import pandas as pd
import maxframe.dataframe as md
from maxframe import new_session
from maxframe.config import options
from maxframe.learn.contrib.llm import ImageContentType
from maxframe.learn.utils import read_odps_model
from odps import ODPS

# Configure the execution engine: DPE first
options.dag.settings = {
    "engine_order": ["DPE", "MCSQL"],
}

# 1. Create an ODPS connection
o = ODPS(
    os.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
    os.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
    project="<your-project-name>",
    endpoint="<your-endpoint>",  # Example: https://service.cn-shanghai.maxcompute.aliyun.com/api
)

# 2. Configure the engine and create a session

# Inference for Model Studio (Bailian) VL models runs on the DPE engine and is billed based on token consumption. You do not need to provision CU or GU resources.

# Create a MaxFrame session
session = new_session(o)
print(f"Session ID: {session.session_id}")
print(f"Logview: {session.get_logview_address()}")

# Load the VL model from the Model Studio (Bailian) public model set
image_llm = read_odps_model(
    "qwen3.6-plus", project="bigdata_public_modelset", odps_entry=o
)

## 4. Prepare image data from OSS

# Use the `oss://<endpoint>/<bucket>/<path>` format and pass your OSS access credentials through `storage_options`.
# OSS configuration
OSS_ENDPOINT = "oss-cn-shanghai-internal.aliyuncs.com"  # Replace with your OSS endpoint
OSS_BUCKET = "your-bucket"                              # Replace with your bucket name
OSS_PREFIX = "images"                                   # Replace with the image path prefix

storage_options = {
    "access_key_id": os.getenv("OSS_ACCESS_KEY_ID"),
    "access_key_secret": os.getenv("OSS_ACCESS_KEY_SECRET"),
}

# Construct a list of image URLs
image_urls = [
    f"oss://{OSS_ENDPOINT}/{OSS_BUCKET}/{OSS_PREFIX}/image{i}.jpg"
    for i in range(1, 9)
]

df = md.DataFrame({"image_url": image_urls})
df.execute()

## 5. Call the VL model for image understanding

# Pass the text prompt and OSS images to the model by using the `generate()` interface.

cp = image_llm.content_part

result_df = image_llm.generate(
    df,
    messages=[
        {
            "role": "user",
            "content": [
                cp.text("Describe this image in one sentence"),
                cp.image(
                    data=df.image_url,
                    type=ImageContentType.IMAGE_URL,
                    storage_options=storage_options,
                ),
            ],
        }
    ],
    simple_output=True,
    params={"max_tokens": 128},
)

## 6. Run the inference and view the results

# MaxFrame uses lazy execution. Call .execute() to trigger the actual computation.
result = result_df.execute()
print(result)

## 7. Clean up resources
session.destroy()
print("Session destroyed")

Performance optimization

Parallel inference

MaxFrame usesparallel computing to perform large-scale offline inference:

  1. Data sharding: The rebalance interface distributes the input data table evenly across multiple worker nodes based on a specified number of partitions (num_partitions).

  2. Parallel model loading: Each worker loads and pre-warms the model independently to prevent cold-start latency.

  3. Result aggregation: MaxFrame aggregates and writes results to a MaxCompute table by partition for subsequent analysis.

Common performance tuning recommendations

  1. Switch heterogeneous computing resources

    CPU-based inference is inefficient for large models, such as those with 8B or more parameters. For these models, switch to GU Quota computing resources or Inference Quota resources.

  2. Process data partitions in parallel

    For inference jobs on large-scale data, you can use therebalance interface to shard the data and process it in parallel.