이 페이지에서는 MLTransform 특성을 사용하여 머신러닝(ML) 모델을 학습시킬 수 있는 데이터를 준비하는 이유와 방법을 설명합니다. 특히 이 페이지에서는 MLTransform을 사용해 임베딩을 생성하여 데이터를 처리하는 방법을 보여줍니다.
한 클래스에 여러 데이터 처리 변환을 결합하면 MLTransform에서 Apache Beam ML 데이터 처리 작업을 워크플로에 적용하는 프로세스를 간소화합니다.
그림 1. 전체 Dataflow ML 워크플로. 워크플로의 전처리 단계에서 MLTransform을 사용합니다.
임베딩 개요
임베딩은 최신 시맨틱 검색 및 검색 증강 생성(RAG) 애플리케이션에서 핵심적인 역할을 합니다. 임베딩을 사용하면 시스템이 더 깊고 개념적인 수준에서 정보를 이해하고 상호작용할 수 있습니다. 시맨틱 검색에서 임베딩은 쿼리와 문서를 벡터 표현으로 변환합니다. 이러한 표현은 기본 의미와 관계를 포착할 수 있도록 합니다.
이를 통해 키워드가 정확하게 일치하지 않아도 관련성 높은 결과를 찾을 수 있습니다. 이는 표준 키워드 기반 검색을 뛰어넘는 큰 발전입니다.
또한 임베딩은 제품 추천에도 사용할 수도 있습니다. 여기에는 이미지와 텍스트를 함께 사용하는 멀티모달 검색, 로그 분석, 중복 제거와 같은 작업이 포함됩니다.
RAG에서는 임베딩이 기술 자료에서 가장 관련성 높은 컨텍스트를 검색하여 대규모 언어 모델(LLM)의 응답 생성에 핵심적인 역할을 합니다. RAG 시스템은 사용자 질문과 기술 자료의 정보 조각을 모두 임베딩하여, 의미적으로 가장 유사한 항목을 효율적으로 식별하고 검색합니다. 이렇게 시맨틱 매칭된 정보를 기반으로 LLM은 보다 정확하고 유익한 답변을 생성할 수 있습니다.
임베딩을 위한 데이터 수집 및 처리
그림 2. 지식 수집 다이어그램. 이 다이어그램은 멀티모달 문서 데이터를 입력으로 받아 처리하는 청킹과 임베딩 생성의 두 단계를 보여줍니다. 청킹은 임베딩 생성 전에 복잡한 데이터를 전처리하는 단계입니다. 데이터가 처리되면 임베딩이 벡터 데이터베이스에 저장됩니다.
임베딩의 핵심 사용 사례에서는 지식을 어떻게 수집하고 처리할지가 가장 중요한 고려 사항입니다. 이 수집은 배치 방식일 수도 있고, 스트리밍 방식일 수도 있습니다. 지식의 소스 또한 매우 다양할 수 있습니다. 예를 들어 Cloud Storage에 저장된 파일이 될 수도 있고, Pub/Sub 또는 Google Cloud의 Apache Kafka 관리형 서비스와 같은 스트리밍 소스에서 시작될 수도 있습니다.
스트리밍 소스의 경우 데이터 자체는 일반 텍스트와 같은 원시 콘텐츠일 수도 있고, 문서를 가리키는 URI일 수도 있습니다. 소스와 관계없이, 첫 번째 단계는 일반적으로 정보를 전처리하는 것입니다. 원시 텍스트의 경우에는 간단한 데이터 정리 작업만으로 충분할 수 있습니다. 하지만 문서가 크거나 콘텐츠가 복잡한 경우에는 청킹이 중요한 단계입니다. 청킹이란 소스 자료를 더 작고 다루기 수윈 단위로 나누는 작업입니다. 어떤 방식으로 청킹할지는 표준화된 방법이 없으며, 사용하는 데이터와 적용 사례에 따라 달라집니다.
Dataflow 같은 플랫폼은 다양한 청킹 요구를 처리할 수 있는 내장 기능을 제공하여, 이 필수적인 전처리 단계를 보다 쉽게 수행할 수 있도록 도와줍니다.
이점
MLTransform 클래스는 다음과 같은 이점을 제공합니다.
데이터를 벡터 데이터베이스로 푸시하거나 추론을 실행하는 데 사용할 수 있는 임베딩을 생성합니다.
복잡한 코드를 작성하거나 기본 라이브러리를 관리하지 않고도 데이터를 변환할 수 있습니다.
인터페이스 하나에서 여러 유형의 처리 작업을 효율적으로 연결할 수 있습니다.
지원 및 제한 사항
MLTransform 클래스에는 다음과 같은 제한사항이 있습니다.
Apache Beam Python SDK 버전 2.53.0 이상을 사용하는 파이프라인에서 사용 가능합니다.
Hugging Face Hub 모델과 함께 Apache Beam MLTransform 클래스를 사용하여 텍스트 임베딩을 생성합니다. Hugging Face SentenceTransformers 프레임워크는 Python을 사용하여 문장, 텍스트, 이미지 임베딩을 생성합니다.
Hugging Face Hub 모델과 함께 Apache Beam, 특히 MLTransform 클래스를 사용하여 텍스트 임베딩을 생성합니다. 이후, VectorDatabaseWriteTransform를 사용해 생성된 임베딩과 관련 메타데이터를 PostgreSQL용 AlloyDB에 로드합니다. 이 노트북에서는 Beam을 활용해 PostgreSQL용 AlloyDB 벡터 데이터베이스에 데이터를 채우는 확장 가능한 일괄 및 스트리밍 파이프라인을 빌드하는 방법을 보여줍니다. 여기에는 Pub/Sub나 기존 데이터베이스 테이블과 같은 다양한 소스로부터 데이터를 처리하고, 커스텀 스키마를 만들고, 데이터를 업데이트하는 작업이 포함됩니다.
Hugging Face Hub 모델과 함께 Apache Beam MLTransform 클래스를 사용하여 제품 카탈로그와 같은 애플리케이션 데이터로부터 텍스트 임베딩을 생성합니다.
이를 위해 Apache Beam HuggingfaceTextEmbeddings 변환이 사용됩니다.
이 변환은 문장 및 텍스트 임베딩 생성을 위한 모델을 제공하는 Hugging Face SentenceTransformers 프레임워크를 사용합니다. 이렇게 생성된 임베딩과 관련 메타데이터는 Apache Beam VectorDatabaseWriteTransform을 사용하여 BigQuery에 수집됩니다.
이 노트북에서는 보강 변환을 사용해 BigQuery에서 벡터 유사도 검색을 수행하는 방법도 함께 설명합니다.
MLTransform 클래스를 사용하여 정보를 청킹하고 임베딩을 생성하려면 파이프라인에 다음 코드를 포함합니다.
defcreate_chunk(product:Dict[str,Any])-> Chunk:returnChunk(content=Content(text=f"{product['name']}: {product['description']}"),id=product['id'],# Use product ID as chunk IDmetadata=product,# Store all product info in metadata)[...]withbeam.Pipeline()asp:_=(p|'Create Products' >> beam.Create(products)|'Convert to Chunks' >> beam.Map(create_chunk)|'Generate Embeddings' >> MLTransform(write_artifact_location=tempfile.mkdtemp()).with_transform(huggingface_embedder)|'Write to AlloyDB' >> VectorDatabaseWriteTransform(alloydb_config))
앞선 예시에서는 각 요소를 하나의 청크로 만들었지만, 대신 LangChain을 사용하여 여러 개의 청크로 나눌 수도 있습니다.
splitter=CharacterTextSplitter(chunk_size=100,chunk_overlap=20)provider=beam.ml.rag.chunking.langchain.LangChainChunker(document_field='content',metadata_fields=[],text_splitter=splitter)withbeam.Pipeline()asp:_=(p|'Create Products' >> beam.io.textio.ReadFromText(products)|'Convert to Chunks' >> provider.get_ptransform_for_processing()
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-10(UTC)"],[],[],null,["This page explains why and how to use the [`MLTransform`](https://github.com/apache/beam/blob/3d501ee9dc208af2efef009daa98c49819b73ddc/sdks/python/apache_beam/ml/transforms/base.py#L112) feature to prepare\nyour data for training machine learning (ML) models. Specifically, this page\nshows you how to process data by generating embeddings using `MLTransform`.\n\nBy\ncombining multiple data processing transforms in one class, `MLTransform`\nstreamlines the process of applying Apache Beam ML data processing\noperations to your workflow.\n\n**Figure 1.** The complete Dataflow ML workflow. Use `MLTransform` in the preprocessing step of the workflow.\n\nEmbeddings overview\n\nEmbeddings are essential for modern semantic search and Retrieval Augmented\nGeneration (RAG) applications. Embeddings let systems understand and interact\nwith information on a deeper, more conceptual level. In semantic search,\nembeddings transform queries and documents into vector representations. These\nrepresentations capture their underlying meaning and relationships.\nConsequently, this lets you find relevant results even when keywords don't\ndirectly match. This is a significant leap beyond standard keyword-based search.\nYou can also use embeddings for product recommendations. This includes\nmultimodal searches that use images and text, log analytics, and for tasks such\nas deduplication.\n\nWithin RAG, embeddings play a crucial role in retrieving the most relevant\ncontext from a knowledge base to ground the responses of large language models\n(LLMs). By embedding both the user's query and the chunks of information in the\nknowledge base, RAG systems can efficiently identify and retrieve the most\nsemantically similar pieces. This semantic matching ensures that the LLM has\naccess to the necessary information to generate accurate and informative\nanswers.\n\nIngest and process data for embeddings\n\n**Figure 2.** A knowledge ingestion diagram. This shows the input multimodal documents data and two processing steps: chunking and embedding generation. Chunking is a preprocessing step used for complex data before embedding generation. After the data is processed, the embeddings are stored in a vector database.\n\nFor core embedding use cases, the key consideration is how to ingest and process\nknowledge. This ingestion can be either in a batch or streaming manner. The\nsource of this knowledge can vary widely. For example, this information can come\nfrom files stored in Cloud Storage,\nor can come from streaming sources like Pub/Sub or\nGoogle Cloud Managed Service for Apache Kafka.\n\nFor streaming sources, the data itself might be the raw content (for example,\nplain text) or URIs pointing to documents. Regardless of the source, the first\nstage typically involves preprocessing the information. For raw text, this might\nbe minimal, such as basic data cleaning. However, for larger documents or more\ncomplex content, a crucial step is *chunking*. Chunking involves breaking down\nthe source material into smaller, manageable units. The optimal chunking\nstrategy isn't standardized and depends on the specific data and application.\nPlatforms like Dataflow offer built-in capabilities to handle\ndiverse chunking needs, simplifying this essential preprocessing stage.\n\nBenefits\n\nThe `MLTransform` class provides the following benefits:\n\n- Generate embeddings that you can use to push data into vector databases or to run inference.\n- Transform your data without writing complex code or managing underlying libraries.\n- Efficiently chain multiple types of processing operations with one interface.\n\nSupport and limitations\n\nThe `MLTransform` class has the following limitations:\n\n- Available for pipelines that use the Apache Beam Python SDK versions 2.53.0 and later.\n- Pipelines must use [default\n windows](https://beam.apache.org/documentation/programming-guide/#single-global-window).\n\n**Text embedding transforms:**\n\n- Support Python 3.8, 3.9, 3.10, 3.11, and 3.12.\n- Support both batch and streaming pipelines.\n- Support the [Vertex AI text-embeddings API](/vertex-ai/docs/generative-ai/embeddings/get-text-embeddings) and the [Hugging Face Sentence Transformers module](https://huggingface.co/sentence-transformers).\n\nUse cases\n\nThe example notebooks demonstrate how to use `MLTransform` for specific use\ncases.\n\n[I want to generate text embeddings for my LLM by using Vertex AI](/dataflow/docs/notebooks/vertex_ai_text_embeddings)\n: Use the Apache Beam `MLTransform` class with the\n [Vertex AI text-embeddings API](/vertex-ai/docs/generative-ai/embeddings/get-text-embeddings)\n to generate text embeddings. Text embeddings are a way to\n represent text as numerical vectors, which is necessary for many natural\n language processing (NLP) tasks.\n\n[I want to generate text embeddings for my LLM by using Hugging Face](/dataflow/docs/notebooks/huggingface_text_embeddings)\n: Use the Apache Beam `MLTransform` class with\n [Hugging Face Hub](https://huggingface.co/docs/hub/models-the-hub)\n models to generate text embeddings. The Hugging Face\n [`SentenceTransformers`](https://huggingface.co/sentence-transformers)\n framework uses Python to generate sentence, text, and image embeddings.\n\n[I want to generate text embeddings and ingest them into AlloyDB for PostgreSQL](/dataflow/docs/notebooks/alloydb_product_catalog_embeddings)\n: Use Apache Beam, specifically its `MLTransform` class with [Hugging Face\n Hub](https://huggingface.co/docs/hub/models-the-hub) models to generate\n text embeddings. Then, use the `VectorDatabaseWriteTransform` to load these\n embeddings and associated metadata into AlloyDB for PostgreSQL. This notebook\n demonstrates building scalable batch and streaming Beam data\n pipelines for populating an AlloyDB for PostgreSQL vector database. This\n includes handling data from various sources like Pub/Sub or existing\n database tables, making custom schemas, and updating data.\n\n[I want to generate text embeddings and ingest them into BigQuery](/dataflow/docs/notebooks/bigquery_vector_ingestion_and_search)\n: Use the Apache Beam `MLTransform` class with [Hugging Face Hub](https://huggingface.co/docs/hub/models-the-hub) models\n to generate text embeddings from application data, such as a product catalog.\n The Apache Beam `HuggingfaceTextEmbeddings` transform is used for this.\n This transform uses the Hugging Face [SentenceTransformers](https://huggingface.co/sentence-transformers) framework,\n which provides models for generating sentence and text embeddings. These\n generated embeddings and their metadata are then ingested into\n BigQuery using the Apache Beam `VectorDatabaseWriteTransform`.\n The notebook further demonstrates vector similarity searches in\n BigQuery using the Enrichment transform.\n\nFor a full list of available transforms, see [Transforms](https://beam.apache.org/documentation/ml/preprocess-data#transforms) in the\nApache Beam documentation.\n\nUse MLTransform for embedding generation\n\nTo use the `MLTransform` class to chunk information and generate embeddings,\ninclude the following code in your pipeline: \n\n \n def create_chunk(product: Dict[str, Any]) -\u003e Chunk:\n return Chunk(\n content=Content(\n text=f\"{product['name']}: {product['description']}\"\n ),\n id=product['id'], # Use product ID as chunk ID\n metadata=product, # Store all product info in metadata\n )\n\n \u003cvar translate=\"no\"\u003e\u003cspan class=\"devsite-syntax-p\"\u003e[\u003c/span\u003e\u003cspan class=\"devsite-syntax-o\"\u003e...\u003c/span\u003e\u003cspan class=\"devsite-syntax-p\"\u003e]\u003c/span\u003e\u003c/var\u003e\n with beam.Pipeline() as p:\n _ = (\n p\n | 'Create Products' \u003e\u003e beam.Create(products)\n | 'Convert to Chunks' \u003e\u003e beam.Map(create_chunk)\n | 'Generate Embeddings' \u003e\u003e MLTransform(\n write_artifact_location=tempfile.mkdtemp())\n .with_transform(huggingface_embedder)\n | 'Write to AlloyDB' \u003e\u003e VectorDatabaseWriteTransform(alloydb_config)\n )\n\nThe previous example creates a single chunk per element, but you can also use\nLangChain for to create chunks instead: \n\n splitter = CharacterTextSplitter(chunk_size=100, chunk_overlap=20)\n provider = beam.ml.rag.chunking.langchain.LangChainChunker(\n document_field='content', metadata_fields=[], text_splitter=splitter)\n\n with beam.Pipeline() as p:\n _ = (\n p\n | 'Create Products' \u003e\u003e beam.io.textio.ReadFromText(products)\n | 'Convert to Chunks' \u003e\u003e provider.get_ptransform_for_processing()\n\nWhat's next\n\n- Read the blog post [\"How to enable real time semantic search and RAG\n applications with Dataflow ML\"](https://cloud.google.com/blog/topics/developers-practitioners/create-and-retrieve-embeddings-with-a-few-lines-of-dataflow-ml-code?content_ref=how+to+enable+real+time+semantic+search+and+rag+applications+with+dataflow+ml).\n- For more details about `MLTransform`, see [Preprocess data](https://beam.apache.org/documentation/ml/preprocess-data) in the Apache Beam documentation.\n- For more examples, see [`MLTransform` for data processing](https://beam.apache.org/documentation/transforms/python/elementwise/mltransform) in the Apache Beam transform catalog.\n- Run an [interactive notebook in Colab](https://colab.sandbox.google.com/github/apache/beam/blob/master/examples/notebooks/beam-ml/mltransform_basic.ipynb)."]]