十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

Feast PyTorch NLP 模板实战:用 Feature Store 构建实时情感分析流水线

Feast PyTorch NLP 模板实战:用 Feature Store 构建实时情感分析流水线 Feast PyTorch NLP 模板实战用 Feature Store 构建实时情感分析流水线【免费下载链接】feastThe Open Source Feature Store for AI/ML项目地址: https://gitcode.com/GitHub_Trending/fe/feast本文以 Feast 官方 PyTorch NLP 模板pytorch_nlp为主线讲解如何将Feast 特征存储、PyTorch / Hugging Face Transformers 预训练模型与实时在线特征服务组合成一条完整的 NLP 情感分析流水线。通过本文你将掌握feast init -t pytorch_nlp生成的模板结构、特征视图与特征服务的定义方式、SQLite 本地零依赖配置、HTTP 特征服务器查询以及静态工件加载Static Artifacts Loading这一将模型在服务启动时一次性载入内存、显著降低推理延迟的关键优化模式并能够基于模板自主扩展特征与模型。模板能做什么一条完整的 NLP MLOps 流水线pytorch_nlp是 Feast 内置模板之一位于仓库 sdk/python/feast/templates/pytorch_nlp它完整演示了现代 MLOps 中 NLP 场景的标准做法Feast 基础能力实体Entity、特征视图Feature View、按需特征视图On-Demand Feature View与特征服务Feature ServiceNLP 特征工程对文本做长度、词数、感叹号数、大写字母占比、emoji 数等统计特征抽取PyTorch 集成在按需特征视图中调用 Hugging Face 预训练情感分析模型CardiffNLP Twitter-RoBERTa实时服务通过feast serve启动 HTTP 特征服务器为生产推理提供在线特征MLOps 模式模型版本化多版本特征服务、性能评估与数据治理TTL、标签、描述。模板核心文件与说明如下仓库路径文件作用feature_repo/example_repo.py全部特征定义实体、特征视图、按需特征视图、特征服务feature_repo/feature_store.yamlFeast 配置本地 provider、SQLite 在线存储、文件离线存储feature_repo/static_artifacts.py服务启动时预加载模型与查找表的静态工件加载逻辑feature_repo/test_workflow.py覆盖训练数据检索、在线推理、按需预测、特征服务的完整演示脚本bootstrap.pyfeast init时生成 1000 条合成情感样本并写入 parquet快速开始五分钟跑通本地示例前置条件Python 3.8pip 或 conda 包管理工具1. 初始化项目feast init my-sentiment-project -t pytorch_nlp cd my-sentiment-projectfeast init会调用模板的 bootstrap.py它在feature_repo/data/下生成包含 1000 条合成文本的sentiment_data.parquet并把项目名中不合法的字符如连字符替换为下划线——因为 SQLite 表名不允许包含连字符这一点在 bootstrap 中会打印提示。2. 安装依赖# 安装 Feast 及其 NLP 相关依赖包含 PyTorch、transformers 与 ML 工具链 pip install feast[nlp]若使用端到端演示还需显式安装模型依赖pip install torch2.0.0 transformers4.30.03. 应用并物化特征cd feature_repo feast apply feast materialize-incremental $(date -u %Y-%m-%dT%H:%M:%S)feast apply把实体、特征视图与特征服务注册进 registry本模板为data/registry.db的 SQLite registryfeast materialize-incremental将离线 parquet 数据按时间范围增量写入在线存储本模板为 SQLite 在线存储。4. 启动特征服务器feast serve --host 0.0.0.0 --port 65665.可选运行完整演示脚本python test_workflow.py模板内置的样本数据与特征工程样本数据集1000 条合成文本样本带正/负/中性三种情感标签已工程化的特征文本长度、词数、emoji 数等用户上下文用户级聚合统计与行为模式动态时间戳生成在过去 30 天内的时间戳保证materialize-incremental演示效果真实。从 bootstrap.py 的源码可以看到数据生成细节40 条来自社交、产品评论、日常生活、新闻等领域的多样化模板文本循环扩样到 1000 条每条文本按概率追加!、...或 emoji如正向文本加、负向文本加以增强多样性优先使用真实分类器若已安装transformers则用finiteautomata/bertweet-base-sentiment-analysisBERTweet针对 Twitter 情感训练打标并把POS/NEG/NEU映射为positive/negative/neutral无分类器时回退到规则法基于正负情感词表amazing/love/great...与terrible/horrible/awful...统计计数给出标签与置信度每个样本生成text_length、word_count、exclamation_count、caps_ratio、emoji_count按ord(c) 127近似判定 emoji等工程化特征按user_id分组聚合出user_avg_sentiment、user_text_count、user_avg_text_length用户级特征合并回主表后写入 parquet。特征工程流水线文本特征内容、元数据与语言学特征text_features特征视图用户特征历史情感模式与参与度指标user_stats特征视图实时特征基于预训练模型的按需情感预测sentiment_prediction按需特征视图。特征仓库源码剖析核心组件逐一拆解模板的特征定义集中在 feature_repo/example_repo.py下面按 Feast 的对象模型拆解。实体Entities实体是特征连接的主键模板定义了两个text_entity Entity( nametext, join_keys[text_id], value_typeValueType.STRING, descriptionUnique identifier for text samples, ) user_entity Entity( nameuser, join_keys[user_id], value_typeValueType.STRING, descriptionUser who created the text content, )text文本样本的唯一标识user内容创建者。数据源与特征视图Feature Views数据源指向 bootstrap 生成的 parquet 文件event_timestamp作为时间戳字段sentiment_source FileSource( namesentiment_data_source, pathstr(data_path / sentiment_data.parquet), timestamp_fieldevent_timestamp, created_timestamp_columncreated, )text_features特征视图保存原始文本与工程化特征TTL 为 7 天text_features_fv FeatureView( nametext_features, entities[text_entity], ttltimedelta(days7), # 特征保留 7 天 schema[ Field(nametext_content, dtypeString, descriptionRaw text content), Field(namesentiment_label, dtypeString, descriptionGround truth sentiment label), Field(namesentiment_score, dtypeFloat32, descriptionGround truth sentiment score), Field(nametext_length, dtypeInt64, descriptionCharacter count of text), Field(nameword_count, dtypeInt64, descriptionWord count of text), Field(nameexclamation_count, dtypeInt64, descriptionNumber of exclamation marks), Field(namecaps_ratio, dtypeFloat32, descriptionRatio of capital letters), Field(nameemoji_count, dtypeInt64, descriptionNumber of emoji characters), ], onlineTrue, sourcesentiment_source, tags{team: nlp, domain: sentiment_analysis}, versionlatest, )user_stats特征视图保存用户级聚合特征TTL 为 30 天用户行为变化频率更低user_stats_fv FeatureView( nameuser_stats, entities[user_entity], ttltimedelta(days30), schema[ Field(nameuser_avg_sentiment, dtypeFloat32, descriptionUsers average sentiment score), Field(nameuser_text_count, dtypeInt64, descriptionTotal number of texts by user), Field(nameuser_avg_text_length, dtypeFloat32, descriptionUsers average text length), ], onlineTrue, sourcesentiment_source, tags{team: nlp, domain: user_behavior}, versionlatest, )注意versionlatest与entity_key_serialization_version配置配合是 Feast 特征视图版本化Feature View Versioning能力的体现相关背景可参考 docs/reference/alpha-feature-view-versioning.md。按需特征视图On-Demand Feature View实时情感预测按需特征视图在请求时即时计算。模板定义了一个RequestSource请求源用于接收推理时刻的输入再定义sentiment_prediction按需特征视图调用预加载的模型text_input_request RequestSource( nametext_input, schema[ Field(nameinput_text, dtypeString, descriptionText to analyze at request time), Field(namemodel_name, dtypeString, descriptionModel to use for prediction), ], ) on_demand_feature_view( sources[text_input_request], schema[ Field(namepredicted_sentiment, dtypeString), Field(namesentiment_confidence, dtypeFloat32), Field(namepositive_prob, dtypeFloat32), Field(namenegative_prob, dtypeFloat32), Field(nameneutral_prob, dtypeFloat32), Field(nametext_embedding, dtypeArray(Float32)), ], ) def sentiment_prediction(inputs: pd.DataFrame) - pd.DataFrame: ...其输出包括预测情感类别、置信度、正/负/中性三分类概率分布以及 384 维文本向量模板中为演示用的随机向量生产环境应使用预计算 embedding。实现细节源码级函数从全局引用_sentiment_model、_lookup_tables读取预加载工件用查找表sentiment_labels把模型的LABEL_0/LABEL_1/LABEL_2映射为negative/neutral/positive取置信度最高的预测作为结果若模型不可用则返回中性兜底预测置信度 0.5、三分类概率 0.33/0.33/0.34保证演示流程不因缺依赖而中断。特征服务Feature Services特征服务把相关特征分组打包供训练与在线推理按版本取用sentiment_analysis_v1 FeatureService( namesentiment_analysis_v1, features[ text_features_fv[[text_content, text_length, word_count]], sentiment_prediction, ], descriptionBasic sentiment analysis features for model v1, ) sentiment_analysis_v2 FeatureService( namesentiment_analysis_v2, features[ text_features_fv, # 全部文本特征 user_stats_fv[[user_avg_sentiment, user_text_count]], # 用户上下文 sentiment_prediction, # 实时预测 ], descriptionAdvanced sentiment analysis with user context for model v2, ) sentiment_training_features FeatureService( namesentiment_training_features, features[text_features_fv, user_stats_fv], descriptionHistorical features for model training and evaluation, )sentiment_analysis_v1面向简单模型的基础情感特征sentiment_analysis_v2带用户上下文的进阶特征集sentiment_training_features仅含历史特征的训练特征服务专供训练与评估。本地配置零外部依赖的 SQLite 方案模板默认面向本地开发无需 Redis 或云服务。feature_repo/feature_store.yaml 完整内容如下project: my_project provider: local registry: data/registry.db online_store: type: sqlite path: data/online_store.db offline_store: type: file entity_key_serialization_version: 3各字段含义与取值配置项值说明projectmy_projectFeast 项目名用于隔离特征仓库providerlocal本地 provider不依赖任何云服务registrydata/registry.db注册表存储位置SQLite 文件online_store.typesqlite在线存储类型为 SQLite非 Redisonline_store.pathdata/online_store.db在线存储本地文件offline_store.typefile离线存储基于本地文件parquetentity_key_serialization_version3实体键序列化版本为什么选 SQLite✅ 零配置——feast init后立即可用✅ 自包含——所有数据都在本地文件✅ 无外部服务——不需要 Redis/云资源✅ 演示友好——易于分享和理解。通过 HTTP Feature Server 查询特征启动feast serve --host 0.0.0.0 --port 6566后可通过POST /get-online-features查询。服务端实现见 sdk/python/feast/feature_server.py该端点接受GetOnlineFeaturesRequestentities为必填feature_service与features二选一内部走store.get_online_features并支持权限校验与审计日志。查询已物化的基础特征curl -X POST \ http://localhost:6566/get-online-features \ -H Content-Type: application/json \ -d { features: [ text_features:text_content, text_features:sentiment_label, user_stats:user_avg_sentiment ], entities: { text_id: [text_0000, text_0001], user_id: [user_080, user_091] } }示例响应{ metadata: {feature_names: [text_id,user_id,sentiment_label,text_content,user_avg_sentiment]}, results: [ {values: [text_0000], statuses: [PRESENT]}, {values: [user_080], statuses: [PRESENT]}, {values: [positive], statuses: [PRESENT]}, {values: [Having an amazing day at the beach with friends!], statuses: [PRESENT]}, {values: [0.905], statuses: [PRESENT]} ] }statuses字段中的PRESENT表示该实体键在在线存储中命中。按需情感预测实时推理curl -X POST \ http://localhost:6566/get-online-features \ -H Content-Type: application/json \ -d { features: [ sentiment_prediction:predicted_sentiment, sentiment_prediction:sentiment_confidence, sentiment_prediction:positive_prob ], entities: { input_text: [I love this amazing product!, This service is terrible], model_name: [cardiffnlp/twitter-roberta-base-sentiment-latest, cardiffnlp/twitter-roberta-base-sentiment-latest] } }这里的input_text与model_name对应RequestSource中定义的字段按需特征视图会在请求时调用预加载模型实时计算。通过特征服务一次取全量特征curl -X POST \ http://localhost:6566/get-online-features \ -H Content-Type: application/json \ -d { feature_service: sentiment_analysis_v2, entities: { text_id: [text_0000], user_id: [user_080], input_text: [This is an amazing experience!], model_name: [cardiffnlp/twitter-roberta-base-sentiment-latest] } }注意请使用生成数据中实际存在的实体组合。可运行head data/sentiment_data.parquet查看可用的text_id与user_id取值在线请求中text_id/user_id用于取已物化特征input_text/model_name用于触发按需计算。静态工件加载把模型在启动时载入内存这是本模板最具实战价值的设计——静态工件加载Static Artifacts Loading对应 Feast 的 alpha 能力正式说明见 docs/reference/alpha-static-artifacts.md。为什么需要它按需特征视图如果每次请求都现场加载模型如反复调用pipeline(sentiment-analysis, model...)会带来巨大的模型加载开销拖慢在线推理。静态工件加载在特征服务器启动时一次性加载模型、查找表等不变资源之后所有请求共享内存中的实例。优化前每请求加载模型def sentiment_prediction(inputs): # ❌ 每个请求都加载模型 - 慢 model pipeline(sentiment-analysis, model...) return model(inputs[text])优化后启动时加载# ✅ 模型只在服务器启动时加载一次 def sentiment_prediction(inputs): global _sentiment_model # 预加载的模型 return _sentiment_model(inputs[text])工作原理三层协作启动钩子feast serve启动时Feast 会在特征仓库根目录查找static_artifacts.py。实现见 sdk/python/feast/feature_server.py 的load_static_artifacts通过importlib动态加载该文件查找load_artifacts(app)函数并执行同步或协程均可任何异常都只是告警而不会导致服务器启动失败。内存存储load_artifacts(app)把工件存入 FastAPI 的app.state。全局引用同时更新example_repo的模块级全局变量按需特征视图通过全局引用直接取用。模板的 static_artifacts.py 完整展示了这一模式# static_artifacts.py - 定义要加载什么 def load_artifacts(app: FastAPI): app.state.sentiment_model load_sentiment_model() app.state.lookup_tables load_lookup_tables() # 更新全局引用便于特征视图直接访问 import example_repo example_repo._sentiment_model app.state.sentiment_model example_repo._lookup_tables app.state.lookup_tables # example_repo.py - 使用预加载工件 _sentiment_model None # 由 static_artifacts.py 注入 def sentiment_prediction(inputs): global _sentiment_model if _sentiment_model is not None: return _sentiment_model(inputs[text]) else: return fallback_predictions()模板中加载的具体工件情感分析模型load_sentiment_model()用transformers.pipeline加载cardiffnlp/twitter-roberta-base-sentiment-latest开启return_all_scoresTrue输出全部类别分数并强制devicecpu避免 macOS MPS 在多进程 fork 下出问题transformers 未安装或加载失败时返回None并记录告警查找表load_lookup_tables()返回sentiment_labelsLABEL_0/1/2 → negative/neutral/positive、emoji_sentiment、domain_categories等静态映射用户向量可选load_user_embeddings()尝试读取data/user_embeddings.npy存在则加载不存在返回None。适用场景与边界✅ 适合中小型模型 1GB如情感分析、文本分类、小型神经网络快速加载的模型查找表与参考数据标签编码器、类别映射配置参数预计算 embedding。❌ 不适合大语言模型LLM——应使用 vLLM、TGI、TensorRT-LLM 等专用推理方案需要 GPU 集群的模型频繁更新的模型初始化依赖复杂的模型。需要明确Feast 面向特征服务而非大模型推理。生产环境的 LLM 负载请交给专用模型服务平台。自定义你的静态工件在static_artifacts.py中扩展即可def load_custom_embeddings(): 加载预计算的用户向量。 embeddings_file Path(__file__).parent / data / user_embeddings.npy if embeddings_file.exists(): import numpy as np return {embeddings: np.load(embeddings_file)} return None def load_artifacts(app: FastAPI): # 加载自定义工件 app.state.custom_embeddings load_custom_embeddings() app.state.config_params {threshold: 0.7, top_k: 10} # 暴露给特征视图 import example_repo example_repo._custom_embeddings app.state.custom_embeddings约定约束来自 docs/reference/alpha-static-artifacts.md文件名必须为static_artifacts.py位于特征仓库根目录且必须实现load_artifacts(app: FastAPI)函数工件同步加载、无内置版本化与热重载。服务器启动日志会输出类似Loading static artifacts from static_artifacts.py的信息。Python SDK 详细用法1. 初始化 FeatureStorefrom feast import FeatureStore store FeatureStore(repo_path.)2. 训练数据检索离线历史特征from datetime import datetime import pandas as pd entity_df pd.DataFrame( { text_id: [text_0000, text_0001, text_0002], user_id: [user_080, user_091, user_052], # 使用实际生成的用户 ID event_timestamp: [datetime.now(), datetime.now(), datetime.now()], } ) training_df store.get_historical_features( entity_dfentity_df, features[ text_features:text_content, text_features:sentiment_label, text_features:text_length, user_stats:user_avg_sentiment, ], ).to_df() print(fRetrieved {len(training_df)} training samples) print(training_df.head())get_historical_features执行 point-in-time 正确的历史特征拼接是离线训练数据的标准取数方式。entity_df中每个实体行需带event_timestampFeast 会据此回放该时刻之前有效的特征值TTL 内。3. 实时在线推理# 使用实际存在的实体组合 entity_rows [ {text_id: text_0000, user_id: user_080}, {text_id: text_0001, user_id: user_091}, ] online_features store.get_online_features( featuresstore.get_feature_service(sentiment_analysis_v1), entity_rowsentity_rows, ).to_dict() print(Online features:, online_features)4. 按需情感预测prediction_rows [ { input_text: I love this product!, model_name: cardiffnlp/twitter-roberta-base-sentiment-latest, } ] predictions store.get_online_features( features[ sentiment_prediction:predicted_sentiment, sentiment_prediction:sentiment_confidence, ], entity_rowsprediction_rows, ).to_dict()端到端演示完整流程与预期输出test_workflow.py 将整个模板流程编排为 8 个步骤feast apply→ 物化 → 训练数据检索 → 模拟训练 → 在线推理 → 按需预测 → 特征服务 → 性能评估。1. 初始化与安装# 创建项目 feast init my-sentiment-demo -t pytorch_nlp cd my-sentiment-demo # 安装依赖 pip install torch2.0.0 transformers4.30.0 # 进入特征仓库 cd feature_repo2. 应用特征定义feast apply预期输出Created entity text Created entity user Created feature view text_features Created feature view user_stats Created on demand feature view sentiment_prediction Created feature service sentiment_analysis_v1 Created feature service sentiment_analysis_v23. 物化特征到在线存储feast materialize-incremental $(date -u %Y-%m-%dT%H:%M:%S)预期输出Materializing 2 feature views to 2025-XX-XX XX:XX:XX00:00 into the sqlite online store. text_features: ████████████████████████████████████████ user_stats: ████████████████████████████████████████4. 启动特征服务器feast serve --host 0.0.0.0 --port 6566预期输出Starting gunicorn 23.0.0 Listening at: http://0.0.0.0:65665. 查询特征在新终端中先确认数据中的真实实体 ID再用 curl 测试# 查看样本实体 python -c import pandas as pd df pd.read_parquet(data/sentiment_data.parquet) print(Sample entities:, df.head()) # 使用真实实体组合测试 curl -X POST \ http://localhost:6566/get-online-features \ -H Content-Type: application/json \ -d { features: [text_features:text_content, text_features:sentiment_label], entities: { text_id: [text_0000], user_id: [user_XXX] } } | jq定制化扩展新增特征字段在example_repo.py的text_features_fvschema 中追加Field(namehashtag_count, dtypeInt64, descriptionNumber of hashtags), Field(namemention_count, dtypeInt64, descriptionNumber of mentions), Field(nameurl_count, dtypeInt64, descriptionNumber of URLs),注意新增字段后需同步在 bootstrap.py 的数据生成逻辑中产出对应列并重新运行feast apply与物化。更换预训练模型修改sentiment_prediction函数中的模型名model_name nlptown/bert-base-multilingual-uncased-sentiment # 或 model_name distilbert-base-uncased-finetuned-sst-2-english模型在 static_artifacts.py 的load_sentiment_model中指定注意同步sentiment_labels查找表以匹配新模型的标签输出。添加自定义转换on_demand_feature_view( sources[text_input_request], schema[Field(nametoxicity_score, dtypeFloat32)], ) def toxicity_detection(inputs: pd.DataFrame) - pd.DataFrame: # 实现毒性检测逻辑 pass生产化考量扩容路径云端部署改用 AWS、GCP 或 Azure provider 替换 local向量存储相似度检索场景下用 Milvus 等向量库替换 SQLite可参考 docs/reference/alpha-vector-database.md模型服务用 KServe 等框架独立部署模型监控增加特征漂移检测与模型性能跟踪参考 docs/how-to-guides/feature-monitoring.md。性能优化当前架构已内置的优化✅ 服务启动时静态工件加载见static_artifacts.py✅ 预加载模型缓存于内存推理无需重复加载✅ 仅用 CPU 以避免多进程问题✅ SQLite 存储保证本地访问速度。已实现的优化手段启动时模型加载模型仅在feast serve启动阶段通过static_artifacts.py载入一次内存友好缓存工件存于app.state通过全局引用共享访问兜底处理工件加载失败时优雅降级返回中性预测服务器照常运行。生产环境可继续追加的优化批量推理多个文本一起处理提升吞吐特征物化把昂贵的特征离线预计算正是feast materialize-incremental在做的事异步处理实时服务采用异步模式模型服务层大模型用 TorchServe、vLLM 等专用模型服务器。生产配置示例演示默认使用 SQLite见上文以下为生产部署参考配置# 生产环境 AWS需要 Redis 服务 project: sentiment_analysis_prod provider: aws registry: s3://my-bucket/feast/registry.pb online_store: type: redis # 需要独立的 Redis 服务器 connection_string: redis://my-redis-cluster:6379 offline_store: type: bigquery project_id: my-gcp-project # 生产环境 GCP需要云服务 project: sentiment_analysis_prod provider: gcp registry: gs://my-bucket/feast/registry.pb online_store: type: redis # 需要独立的 Redis 服务器 connection_string: redis://my-redis-cluster:6379 offline_store: type: bigquery project_id: my-gcp-project故障排查常见问题解决办法ImportError: No module named transformers执行pip install torch transformers模型下载超时设置 Hugging Face 缓存环境变量export HF_HOME/path/to/cache特征存储初始化失败重置特征存储feast teardown后重新feast apply按需特征返回默认值属预期行为PyTorch/transformers 未安装时模板会返回兜底预测安装依赖后即恢复真实推理小结pytorch_nlp模板把 Feast 特征存储与 PyTorch / Hugging Face 生态打通示范了一条从合成数据生成、特征工程、离线训练取数到实时在线推理的完整 NLP MLOps 链路。其核心价值在于两点一是以Entity / FeatureView / On-Demand FeatureView / FeatureService为骨架把文本特征—用户特征—实时模型预测统一到特征存储体系中并用三个特征服务实现模型版本化管理二是通过静态工件加载将模型预热成本从每次请求转移到服务启动期为在按需特征视图中安全使用中小型预训练模型提供了可复制的性能模式。以此为起点你可以将数据源替换为真实业务流Twitter API、产品评论等将模型替换为自有微调模型并把本地 SQLite 方案升级为云厂商的在线/离线存储组合落地到生产。【免费下载链接】feastThe Open Source Feature Store for AI/ML项目地址: https://gitcode.com/GitHub_Trending/fe/feast创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表