ONE is preparing: 01 / INITIALIZING MODEL ROUTER. Evaluating routing across providers.
Current state
01 / INITIALIZING MODEL ROUTER.

Evaluating routing across providers.

Start learning
← Hạ tầng & Vận hành

AI Builder

Đường ống dữ liệu

Vietnamese onlyThe learning content is available in Vietnamese only. The surrounding interface follows your language.

Thiết kế quy trình tự động thu thập, xử lý và chuẩn bị dữ liệu cho huấn luyện mô hình AI

lesson120 minHạ tầng & Vận hànhAI Engineer

Dự đoán

Model gợi ý sản phẩm Shopee cần data mua sắm của 50 triệu user. Data nằm rải ở 5 database khác nhau, cập nhật mỗi phút. Bạn cần gì để model luôn có data mới nhất?

Đúng! Data Pipeline là 'nhà máy chế biến' tự động — nguyên liệu thô (raw data) từ nhiều nguồn được thu thập, làm sạch, biến đổi, và giao đến model sẵn sàng sử dụng. Không có pipeline = data stale, model tệ!

Ẩn dụ: Nhà máy chế biến thực phẩm

Hãy tưởng tượng một nhà máy nước trái cây quy mô công nghiệp. Nguyên liệu (trái cây thô) đến từ nhiều nông trại — đó là nguồn dữ liệu (database, API, Kafka, S3). Nhà máy có 5 dây chuyền nối tiếp:

  • Rửa & phân loại = Ingest: tập trung nguyên liệu về kho.
  • Kiểm định chất lượng = Validate: loại trái thối, sai kích cỡ.
  • Ép, lọc, pha chế = Transform: chuyển raw data thành feature.
  • Đóng chai lưu kho = Feature Store: sản phẩm đã đóng gói sẵn.
  • Giao hàng cho cửa hàng = Training/Serving: model hoặc API dùng feature.

Có quản đốc đứng điều phối cả nhà máy — đó chính là orchestrator (Airflow, Dagster, Prefect). Quản đốc không trực tiếp ép trái cây, nhưng quyết định dây chuyền nào chạy lúc nào, báo động khi máy hỏng, và ghi nhật ký để truy vết lỗi. Không có quản đốc, các dây chuyền không biết thứ tự chạy — chaos.

Batch Pipeline

  • Độ trễ (latency) Giờ → ngày
  • Công cụ phổ biến Airflow · Spark · dbt
  • Ví dụ use case Báo cáo, huấn luyện lại hàng đêm
  • Độ phức tạp Thấp — job có điểm đầu/cuối rõ ràng
  • Khả năng backfill Dễ: replay job là xong
  • Chi phí vận hành Thấp — cluster chạy theo lịch

Streaming Pipeline

  • Độ trễ (latency) Mili-giây → giây
  • Công cụ phổ biến Kafka · Flink · Spark Streaming
  • Ví dụ use case Fraud detection, personalization real-time
  • Độ phức tạp Cao — state management, watermark, exactly-once
  • Khả năng backfill Khó: cần log-replay (Kafka), idempotency
  • Chi phí vận hành Cao — luôn online, tài nguyên 24/7
Dashboard cần cập nhật số đơn hàng mỗi 5 giây. Chọn kiểu pipeline nào?

Airflow DAG — bản thiết kế của pipeline

DAG (Directed Acyclic Graph) là đồ thị có hướng, không chu trình: mỗi node là một task, mỗi cạnh là dependency. Airflow parse file Python, dựng DAG, rồi scheduler chạy task theo đúng thứ tự. Dưới đây là sơ đồ đơn giản của pipeline ví dụ:

3 task ingest song song → validate tập trung → transform → fan-out ghi feature store & trigger training.

Khoảnh khắc Aha

80% thời gian của dự án ML là xử lý dữ liệu, chỉ 20% là train model! Data pipeline tốt = model tốt. Pipeline tệ = "garbage in, garbage out". Giống nhà máy chế biến thực phẩm: nguyên liệu tươi + quy trình sạch = sản phẩm chất lượng. Đầu tư vào pipeline là đầu tư khôn ngoan nhất!

Thử thách 1

Pipeline chạy hàng đêm lúc 2h sáng. Một đêm, bước Transform fail vì data có cột mới (schema change). Sáng hôm sau team mới biết. Thiếu gì trong pipeline?

Data validation (Great Expectations, Pandera) check schema, data types, value ranges TRƯỚC khi transform. Khi fail: alert Slack/PagerDuty ngay lập tức, không đợi đến sáng. Pipeline robustness = validation + alerting + retry + fallback.

Thử thách 2

Team ML thấy online metric của model tụt 20% sau deploy, dù offline metric vẫn tốt. Pipeline training dùng feature A = AVG(last_30_days), serving dùng feature A = AVG(last_7_days). Đây là lỗi gì?

Train-serve skew là lỗi silent killer: offline model học trên distribution A, production chạy trên distribution B. Giải pháp: dùng feature store (Feast, Tecton) có MỘT định nghĩa feature duy nhất cho cả offline (parquet) và online (Redis/DynamoDB). Xem thêm tại bài MLOps.

Sáu giai đoạn cốt lõi

Data Pipeline là quy trình tự động hoá thu thập, xử lý và chuẩn bị dữ liệu từ nguồn đến đích — thành phần không thể thiếu trong mọi hệ thống AI/ML, là nền tảng cho MLOps hoàn chỉnh. Một pipeline tốt đảm bảo dữ liệu đến đúng nơi, đúng lúc, đúng chất lượng, và có thể truy vết (data lineage) khi có sự cố.

Sáu giai đoạn cốt lõi của một ML data pipeline:

  • Source (Nguồn): cơ sở dữ liệu giao dịch (Postgres, MySQL), event stream (Kafka, Kinesis), file storage (S3, GCS), REST API bên thứ ba.
  • Ingestion (Thu thập): Pull hoặc Push từ các nguồn về staging area. Công cụ: Fivetran, Airbyte, Meltano cho batch; Kafka Connect cho streaming.
  • Validation (Xác thực): check schema, data quality, detect anomalies. Great Expectations, Pandera, Soda.
  • Transformation (Biến đổi): clean, normalize, join, aggregate, feature engineering. Spark, dbt, Pandas, Polars.
  • Feature Store (Lưu trữ feature): kho feature có 2 chế độ offline (parquet/BigQuery) và online (Redis/DynamoDB) — Feast, Tecton, Hopsworks.
  • Serving (Phục vụ): API cho training pipeline (đọc offline store) hoặc real-time inference (đọc online store với latency < 10ms).

Chỉ số chất lượng dữ liệu

Công thức độ tươi dữ liệu (data freshness) — chỉ số quan trọng đánh giá pipeline:

freshness=tnow−teventvới {batch:O(giờ)micro-batch:O(phuˊt)streaming:O(giaˆy)\text{freshness} = t_{\text{now}} - t_{\text{event}} \quad \text{với } \begin{cases} \text{batch:} & \mathcal{O}(\text{giờ}) \\ \text{micro-batch:} & \mathcal{O}(\text{phút}) \\ \text{streaming:} & \mathcal{O}(\text{giây}) \end{cases}

Một hàm đánh giá chất lượng dữ liệu tổng hợp:

Q(D)=w1⋅Completeness+w2⋅Accuracy+w3⋅Timeliness+w4⋅Consistency+w5⋅UniquenessQ(D) = w_1 \cdot \text{Completeness} + w_2 \cdot \text{Accuracy} + w_3 \cdot \text{Timeliness} + w_4 \cdot \text{Consistency} + w_5 \cdot \text{Uniqueness}

Code mẫu

1. Airflow DAG — orchestrate pipeline theo lịch

from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow.sensors.filesystem import FileSensor
from airflow.utils.trigger_rule import TriggerRule
from datetime import datetime, timedelta

default_args = {
    "owner": "ml-platform",
    "retries": 3,
    "retry_delay": timedelta(minutes=5),
    "on_failure_callback": alert_slack,  # hook Slack khi fail
    "email_on_failure": True,
    "execution_timeout": timedelta(hours=2),
}

with DAG(
    dag_id="ml_data_pipeline_v2",
    start_date=datetime(2024, 1, 1),
    schedule_interval="0 2 * * *",     # cron: 2:00 AM mỗi ngày
    catchup=False,                      # bỏ qua backfill cũ
    max_active_runs=1,                  # chỉ 1 instance chạy cùng lúc
    default_args=default_args,
    tags=["ml", "feature-store"],
) as dag:

    # --- Bước 0: đợi file CSV từ vendor đến S3 ---
    wait_file = FileSensor(
        task_id="wait_for_raw_file",
        filepath="/data/raw/{{ ds }}/orders.csv",
        poke_interval=60,
        timeout=60 * 60 * 4,  # tối đa 4 giờ
        mode="reschedule",    # nhường slot cho task khác khi đang đợi
    )

    # --- Bước 1: ingest song song từ 3 nguồn ---
    ingest_pg = PythonOperator(
        task_id="ingest_postgres",
        python_callable=ingest_postgres_orders,
    )
    ingest_s3 = PythonOperator(
        task_id="ingest_s3",
        python_callable=ingest_s3_events,
    )
    ingest_api = PythonOperator(
        task_id="ingest_api",
        python_callable=ingest_third_party_api,
    )

    # --- Bước 2: validate tập trung ---
    validate = PythonOperator(
        task_id="validate_schema",
        python_callable=run_great_expectations,
        trigger_rule=TriggerRule.ALL_SUCCESS,   # chỉ chạy nếu 3 ingest OK
    )

    # --- Bước 3: transform với dbt ---
    transform = PythonOperator(
        task_id="transform_dbt",
        python_callable=run_dbt_models,
    )

    # --- Bước 4: fan-out — ghi feature store và trigger training ---
    write_feature = PythonOperator(
        task_id="write_feature_store",
        python_callable=materialize_feast_features,
    )
    trigger_train = PythonOperator(
        task_id="trigger_training",
        python_callable=submit_training_job,
    )

    # --- Dependencies ---
    wait_file >> [ingest_pg, ingest_s3, ingest_api] >> validate
    validate >> transform >> [write_feature, trigger_train]

2. Great Expectations — tầng bảo vệ data quality

import great_expectations as gx

# 1. Context + Datasource
context = gx.get_context()
source = context.sources.add_pandas("orders")
asset = source.add_dataframe_asset("raw_orders")

# 2. Expectation Suite — khai báo "kỳ vọng" về dữ liệu
suite = context.add_expectation_suite("orders_suite")
validator = context.get_validator(
    batch_request=asset.build_batch_request(dataframe=df),
    expectation_suite=suite,
)

# Schema & bắt buộc có
validator.expect_table_columns_to_match_ordered_list(
    column_list=["order_id", "user_id", "amount", "currency", "created_at"]
)
validator.expect_column_values_to_not_be_null("order_id")
validator.expect_column_values_to_be_unique("order_id")

# Miền giá trị
validator.expect_column_values_to_be_between(
    column="amount", min_value=0, max_value=1_000_000_000
)
validator.expect_column_values_to_be_in_set(
    column="currency", value_set=["VND", "USD", "EUR"]
)

# Statistical checks
validator.expect_column_mean_to_be_between(
    column="amount", min_value=50_000, max_value=5_000_000
)

# 3. Save & chạy validation mỗi đêm trong Airflow
validator.save_expectation_suite()
result = validator.validate()
if not result.success:
    raise AirflowException(
        f"Data quality failed: {result.statistics['unsuccessful_expectations']} rules violated"
    )

Các bẫy thiết kế

Airflow vs Dagster vs Prefect

Airflow (2014, Airbnb): thư viện lâu đời nhất, cộng đồng lớn nhất. DAG viết bằng Python đơn thuần. Ưu: plugin bạt ngàn, tài liệu phong phú, có managed service (MWAA, Astronomer, Cloud Composer). Nhược: mô hình task-level khó biểu đạt dataflow phức tạp, UI đôi khi lag, testing DAG hơi cồng kềnh.

Dagster (2019, Elementl): triết lý software-defined assets — thay vì nghĩ theo task, nghĩ theo "dataset" (asset) và pipeline materialize asset. Tích hợp sâu với dbt, Pandas, Polars. Mạnh về type system, testing, observability. Nhược: đường học hơi dốc, cộng đồng nhỏ hơn.

Prefect (2018, Prefect Technologies): code-first, flow-first, hybrid execution (agent chạy ở hạ tầng của bạn nhưng control plane trên cloud). Ưu: API Python rất Pythonic, dễ bắt đầu. Nhược: một số feature enterprise cần trả phí.

Khi nào dùng gì? Team mới, cần nhiều connector sẵn → Airflow. Team dữ liệu mạnh, muốn type-safety + asset-based thinking → Dagster. Team đã quen decorator-based Python, muốn nhẹ → Prefect.

Medallion architecture: Bronze / Silver / Gold

Databricks phổ biến mô hình Medallion để tổ chức data lake thành 3 tầng chất lượng tăng dần:

  • Bronze — raw, append-only, giữ đúng schema nguồn. Mục đích: lưu trữ "nguyên bản lịch sử", có thể replay mọi logic tương lai từ đây.
  • Silver — đã validate, clean, deduplicate, join các bronze table. Đây là tầng "đáng tin cậy" cho analyst và ML team dùng.
  • Gold — aggregated, business-ready: dashboards, KPI, feature store. Mỗi gold table giải đáp một câu hỏi nghiệp vụ cụ thể.

Lợi ích: trách nhiệm rõ ràng (bronze thuộc data engineer, silver thuộc platform, gold thuộc nghiệp vụ), dễ truy vết lỗi, tái tính toán khi logic thay đổi. Áp dụng được cả trên lakehouse (Delta, Iceberg, Hudi) lẫn warehouse (BigQuery + dbt).

Ứng dụng và pitfalls

Ứng dụng thực tế — data pipeline là xương sống của mọi sản phẩm dữ liệu hiện đại:

  • Recommendation (Shopee, TikTok): Kafka ingest event click/view → Flink tính feature rolling (last 30 min) → Feast online store → model re-score trong 50ms.
  • Fraud detection (VPBank, Momo): streaming feature cửa sổ trượt + feature historical batch → XGBoost score real-time.
  • Forecasting (VNG, Grab): batch pipeline hàng đêm aggregate đơn hàng, chạy Prophet/ARIMA, publish dashboard sáng hôm sau.
  • LLM fine-tuning (OpenAI, Anthropic): crawl + clean + dedupe hàng petabyte text → shard parquet → DataLoader streaming cho GPU cluster.
  • IoT & cảm biến (EVN, nhà máy Samsung): MQTT → Kafka → TimescaleDB, pipeline phát hiện anomaly nhiệt độ trong vài giây.

Bẫy thường gặp (pitfalls):

  • Silent data loss: bước ingest thất bại nhưng không alert → pipe vẫn "xanh", dashboard sai lệch âm thầm. Khắc phục: monitor row count, so sánh với baseline.
  • Thiếu idempotency: retry làm duplicate record. Dùng MERGE / upsert / partition-overwrite thay INSERT INTO ... SELECT.
  • Giờ/múi giờ lộn xộn: lưu timestamp mix UTC và giờ địa phương → join sai. Chuẩn hoá về UTC ngay ở bước ingest.
  • Không versioning pipeline code: hotfix trực tiếp trên prod. Dùng Git + CI/CD, deploy DAG qua pull request.
  • Quá nhiều small files: 100k file 1MB ở S3 → đọc cực chậm. Compact lại thành file 128MB–1GB (Parquet, ORC).
  • Bỏ qua cost monitoring: job dbt nhỏ nhưng scan 20TB mỗi lần chạy, hoá đơn BigQuery tăng theo tháng. Dùng partitioning, clustering, incremental dbt models.

Tóm tắt

  • Data Pipeline tự động hoá 6 bước: Source → Ingest → Validate → Transform → Feature Store → Training.
  • 80% thời gian ML là xử lý data. Pipeline tốt = model tốt; 'garbage in, garbage out'.
  • Validation bắt buộc ở cả đầu vào và đầu ra — Great Expectations, Pandera detect anomalies sớm.
  • Batch (latency giờ) cho analytics/retrain, Streaming (latency giây) cho real-time features.
  • Orchestrator (Airflow, Dagster, Prefect) quản lý DAG: thứ tự, retry, alerting, lineage.
  • Feature Store (Feast, Tecton) chống train-serve skew bằng một định nghĩa feature duy nhất cho cả offline lẫn online.

Continue the module

Lesson 9 of 9