[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,90 +2,157 @@
|
||||
id: wiki-2026-0508-tensorflow-foundations
|
||||
title: TensorFlow Foundations
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [AI-TOOL-TF-001]
|
||||
aliases: [TensorFlow, TF2, Keras]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [ai, machine-learning, Deep-Learning, tensorflow, google, keras, tensor, mldev, MLOps]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [tensorflow, deep-learning, keras]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-26
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: Python
|
||||
framework: TensorFlow 2.x / Keras 3
|
||||
---
|
||||
|
||||
# TensorFlow Foundations (텐서플로우 기초)
|
||||
# TensorFlow Foundations
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "데이터를 다차원 배열(Tensor)의 흐름으로 정의하고, 유연한 계산 그래프를 통해 연구실의 아이디어를 전 세계 서비스 인프라로 즉각 확장하라" — 구글이 개발한 세계에서 가장 널리 쓰이는 엔터프라이즈급 오픈소스 머신러닝 프레임워크.
|
||||
## 매 한 줄
|
||||
> **"매 production-first ML framework"**. Google이 2015년에 release한 graph-based deep learning framework. TF 2.x는 eager-by-default + Keras integration으로 PyTorch-like UX를 제공하지만, 매 핵심 강점은 mobile (TFLite) / web (TF.js) / production serving (TF Serving) 의 cross-platform deployment.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Graph-based Computation and Production-ready Ecosystem" — 수학적 연산을 노드와 엣지로 이루어진 그래프로 표현하여 CPU, GPU, TPU 등 다양한 하드웨어에서 최적의 성능으로 실행하고, 모바일(Lite)부터 서버(Serving)까지 끊김 없는 배포 파이프라인을 제공하는 패턴.
|
||||
- **핵심 구성 요소:**
|
||||
- **Tensors:** 데이터를 담는 n-차원 배열.
|
||||
- **Keras API:** 쉽고 빠르게 딥러닝 모델을 설계할 수 있는 고수준 인터페이스.
|
||||
- **Eager Execution:** 파이썬처럼 즉시 연산 결과를 확인할 수 있는 동적 그래프 모드.
|
||||
- **TensorBoard:** 학습 과정을 시각화하고 디버깅하는 강력한 도구.
|
||||
- **TF Ecosystem:** Extended(TFX), Lite, JS, Hub 등 데이터 수집부터 배포까지의 전 과정 지원.
|
||||
- **의의:** 학술적 연구를 넘어 실제 상용 서비스에 AI를 안정적으로 탑재하기 위한 가장 견고한 표준 인프라를 구축함.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 정적 그래프(Static Graph) 중심의 복잡한 구조로 인해 PyTorch에 연구용 시장을 내주기도 했으나, 버전 2.0 이후 Keras를 전면에 내세우고 'Eager Execution'을 기본값으로 채택하며 사용성과 성능이라는 두 마리 토끼를 다시 잡는 데 성공함.
|
||||
- **정책 변화:** Antigravity 프로젝트는 에이전트의 대규모 배포 및 안정적인 추론 서빙(Serving) 인프라 구축 시, 검증된 하드웨어 가속 성능을 제공하는 텐서플로우 생태계의 도구들을 주력으로 활용함.
|
||||
### 매 TF 2.x 의 essence
|
||||
- **Eager execution** default — 매 `tf.function` 으로 graph compile (XLA / autograph).
|
||||
- **Keras** 가 high-level API — 매 `tf.keras.Model` / `Sequential` / Functional API.
|
||||
- **`tf.data`** — 매 efficient input pipeline (prefetch, parallel map, sharding).
|
||||
- **`tf.distribute`** — 매 multi-GPU / TPU strategy (`MirroredStrategy`, `TPUStrategy`).
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- Deep-Learning-Foundations, Neural-Networks-Basics, MLOps-Best-Practices, [[Scalability-in-AI-Systems|Scalability-in-AI-Systems]]
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/TensorFlow-Foundations.md
|
||||
### 매 PyTorch 와 의 비교 (2026)
|
||||
- **연구 share**: PyTorch ~85%, TF ~10%. JAX growing.
|
||||
- **Production share**: TF still dominant (TFLite mobile, TF.js web, TF Serving) thanks to mature deployment.
|
||||
- **Keras 3 (2024+)**: 매 backend-agnostic — TF / JAX / PyTorch 모두 backend로 사용 가능.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. Mobile inference (Android / iOS via TFLite).
|
||||
2. Browser ML (TF.js — pose detection, on-device LLM).
|
||||
3. Recommender systems (TFRS, large embedding tables).
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### Sequential model
|
||||
```python
|
||||
import tensorflow as tf
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
model = tf.keras.Sequential([
|
||||
tf.keras.layers.Dense(128, activation="relu"),
|
||||
tf.keras.layers.Dropout(0.2),
|
||||
tf.keras.layers.Dense(10),
|
||||
])
|
||||
model.compile(optimizer="adam",
|
||||
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
|
||||
metrics=["accuracy"])
|
||||
model.fit(x_train, y_train, epochs=5, validation_split=0.1)
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Functional API (multi-input)
|
||||
```python
|
||||
img_in = tf.keras.Input(shape=(224, 224, 3))
|
||||
txt_in = tf.keras.Input(shape=(128,), dtype="int32")
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
img_feat = tf.keras.applications.EfficientNetV2B0(include_top=False, pooling="avg")(img_in)
|
||||
txt_feat = tf.keras.layers.Embedding(10000, 64)(txt_in)
|
||||
txt_feat = tf.keras.layers.GlobalAveragePooling1D()(txt_feat)
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
x = tf.keras.layers.Concatenate()([img_feat, txt_feat])
|
||||
out = tf.keras.layers.Dense(1, activation="sigmoid")(x)
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
model = tf.keras.Model([img_in, txt_in], out)
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### tf.function (graph compile)
|
||||
```python
|
||||
@tf.function(jit_compile=True) # XLA
|
||||
def train_step(x, y):
|
||||
with tf.GradientTape() as tape:
|
||||
logits = model(x, training=True)
|
||||
loss = loss_fn(y, logits)
|
||||
grads = tape.gradient(loss, model.trainable_variables)
|
||||
optimizer.apply_gradients(zip(grads, model.trainable_variables))
|
||||
return loss
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### tf.data input pipeline
|
||||
```python
|
||||
ds = (tf.data.Dataset.from_tensor_slices((x, y))
|
||||
.shuffle(10000)
|
||||
.map(preprocess, num_parallel_calls=tf.data.AUTOTUNE)
|
||||
.batch(64)
|
||||
.prefetch(tf.data.AUTOTUNE))
|
||||
```
|
||||
|
||||
### Multi-GPU
|
||||
```python
|
||||
strategy = tf.distribute.MirroredStrategy()
|
||||
with strategy.scope():
|
||||
model = build_model()
|
||||
model.compile(...)
|
||||
model.fit(ds, epochs=10)
|
||||
```
|
||||
|
||||
### TFLite export
|
||||
```python
|
||||
converter = tf.lite.TFLiteConverter.from_keras_model(model)
|
||||
converter.optimizations = [tf.lite.Optimize.DEFAULT] # int8 quantization
|
||||
tflite_model = converter.convert()
|
||||
open("model.tflite", "wb").write(tflite_model)
|
||||
```
|
||||
|
||||
### Keras 3 backend swap
|
||||
```python
|
||||
import os
|
||||
os.environ["KERAS_BACKEND"] = "jax" # or "torch", "tensorflow"
|
||||
import keras
|
||||
model = keras.Sequential([keras.layers.Dense(10)])
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Mobile/edge deployment | TF + TFLite (mature) |
|
||||
| Browser inference | TF.js |
|
||||
| Production serving at scale | TF Serving / TFX |
|
||||
| Research / new architectures | PyTorch (ecosystem) |
|
||||
| Backend-agnostic code | Keras 3 |
|
||||
| TPU training | TF or JAX |
|
||||
|
||||
**기본값**: 매 research 는 PyTorch, deployment 는 TF or ONNX export.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Deep-Learning]] · [[Machine-Learning-Foundations]]
|
||||
- 변형: [[PyTorch-Foundations]] · [[JAX-Foundations]] · [[Keras]]
|
||||
- 응용: [[Mobile-ML]] · [[TensorFlow-js]] · [[Recommender-Systems]]
|
||||
- Adjacent: [[ONNX]] · [[Model-Serving]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: mobile/web deployment target, TPU access, legacy TF1 codebase migration, TFX pipeline.
|
||||
**언제 X**: 매 cutting-edge research model 의 reproduce — 매 PyTorch reference impl 의 dominant.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **TF1 graph mode 의 cling**: 매 `tf.compat.v1.Session` 의 use 를 새 code 에서 X — 매 TF2 eager + tf.function.
|
||||
- **Custom training loop 의 unnecessary use**: 매 `model.fit` 으로 충분한 case 에 manual loop 작성.
|
||||
- **`tf.py_function` overuse**: 매 graph 밖 fallback — 매 performance kill.
|
||||
- **No `prefetch`**: 매 input pipeline 이 GPU 의 starve.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (TensorFlow official docs, Keras 3 release notes, 2024-2026 tracking).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — TF2/Keras3 modern usage + deployment focus |
|
||||
|
||||
Reference in New Issue
Block a user