[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,88 +2,135 @@
id: wiki-2026-0508-locality-sensitive-hashing
title: Locality Sensitive Hashing
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [ALGO-LSH-001]
aliases: [LSH, Locality-Sensitive-Hashing, MinHash, SimHash]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [algorithm, Search, lsh, hashing, similarity-search, Big-Data]
confidence_score: 0.93
verification_status: applied
tags: [hashing, ann, similarity-search, embeddings, retrieval]
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: datasketch-faiss
---
# Locality-Sensitive Hashing (LSH, 지역 민감 해싱)
# Locality Sensitive Hashing
## 📌 한 줄 통찰 (The Karpathy Summary)
> "해시 충돌을 '버그'가 아닌 '특징'으로 활용하여, 닮은꼴 데이터들을 같은 바구니에 담아라" — 비슷한 특성을 가진 고차원 데이터들이 높은 확률로 동일한 해시 값을 갖게 하여, 선형 탐색 없이도 유사한 데이터를 매우 빠르게 찾아내는 확률적 근사 검색 기법.
## 한 줄
> **"매 가까운 점은 매 같은 bucket에 떨어진다"**. LSH는 매 metric similarity를 hash collision probability로 변환하여 매 sub-linear ANN(approximate nearest neighbor) search를 가능케 한다. 2026 vector DB 시대에 IVF-PQ·HNSW에 밀렸지만, 매 streaming dedup·document near-dup detection에서 매 dominant.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Probabilistic Bucketing" — 모든 데이터를 전수 조사하는 대신, 유사한 데이터끼리 같은 버킷(Bucket)에 모이도록 설계된 해시 함수를 통해 탐색 범위를 획기적으로 줄이는 고속 검색 패턴.
- **작동 원리:**
- **Projection:** 고차원 벡터를 임의의 축으로 투영하거나 해싱하여 차원 축소.
- **Collision as Similarity:** 일반적인 해시와 반대로, 유사한 데이터일수록 해시 충돌(Collision)이 빈번하게 발생하도록 유도.
- **Candidate Selection:** 동일한 해시 버킷에 담긴 데이터들만을 대상으로 정밀한 유사도 측정 수행.
- **의의:** 수억 건 이상의 데이터가 쌓인 환경에서도 중복 문서 탐지, 유사 이미지 검색, 추천 시스템 등을 실시간 수준으로 처리 가능케 함.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 완전한 정답을 보장하지 못한다는 이유로 외면받기도 했으나, 데이터가 폭발적으로 증가하는 빅데이터 시대에 '완벽한 정답'보다 '충분히 빠른 근사 정답'이 더 가치 있음을 입증하며 필수 알고리즘으로 정착됨.
- **정책 변화:** Antigravity 프로젝트는 1,174개의 방대한 문서 중 중복되거나 유사한 내용이 있는지 전수 검사할 때, 연산 효율을 위해 LSH 기반의 1차 필터링을 수행함.
### 매 family들
- **MinHash (Jaccard)**: 매 set similarity — shingled documents.
- **SimHash (cosine)**: 매 random hyperplane projection.
- **p-stable LSH (L2)**: 매 random Gaussian projection + bucketing.
- **Cross-polytope LSH**: 매 angular distance, 매 unit sphere 위.
## 🔗 지식 연결 (Graph)
- [[Indexing-Strategies|Indexing-Strategies]], Vector-Database-Foundations, [[Dimensionality-Reduction|Dimensionality-Reduction]], [[K-Nearest-Neighbors-K-NN|K-Nearest-Neighbors-K-NN]]
- **Raw Source:** 10_Wiki/Topics/AI/Locality-Sensitive-Hashing.md
### 매 amplification
- AND-construction: 매 k hashes 모두 일치 → false positive ↓.
- OR-construction: 매 L tables 중 하나라도 collision → recall ↑.
- (k, L) tuning이 매 핵심.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Plagiarism / near-duplicate detection (web, code).
2. Streaming deduplication (logs, training data).
3. Genomic sequence matching.
4. Pre-filter for vector DBs at billion scale.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (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
### MinHash with datasketch
```python
from datasketch import MinHash, MinHashLSH
def shingles(text, k=3):
return {text[i:i+k] for i in range(len(text)-k+1)}
m = MinHash(num_perm=128)
for s in shingles(doc):
m.update(s.encode())
lsh = MinHashLSH(threshold=0.7, num_perm=128)
lsh.insert("doc1", m)
matches = lsh.query(m_query)
```
## 🤔 의사결정 기준 (Decision Criteria)
### SimHash (64-bit)
```python
import numpy as np
def simhash(features, bits=64):
v = np.zeros(bits)
for f, w in features:
h = hash(f)
for i in range(bits):
v[i] += w if (h >> i) & 1 else -w
return sum(1 << i for i in range(bits) if v[i] > 0)
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Random projection LSH (cosine)
```python
class CosineLSH:
def __init__(self, dim, n_planes=16):
self.planes = np.random.randn(n_planes, dim)
def hash(self, x):
return tuple((self.planes @ x > 0).astype(int))
```
**선택 B를 써야 할 때:**
- *(TODO)*
### p-stable LSH (Euclidean)
```python
def l2_hash(x, a, b, w):
return int((a @ x + b) // w)
# a ~ N(0, I), b ~ U(0, w)
```
**기본값:**
> *(TODO)*
### Banding for MinHash
```python
def bands(sig, b, r):
return [tuple(sig[i*r:(i+1)*r]) for i in range(b)]
# threshold ~ (1/b)^(1/r)
```
## ❌ 안티패턴 (Anti-Patterns)
### FAISS LSH index (for L2)
```python
import faiss
index = faiss.IndexLSH(dim, n_bits=256)
index.add(X)
D, I = index.search(query, k=10)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| Metric | LSH family |
|---|---|
| Jaccard | MinHash |
| Cosine | SimHash / random hyperplane |
| Euclidean | p-stable / IndexLSH |
| Hamming | Bit sampling |
**기본값**: HNSW 우선, billion-scale dedup만 LSH.
## 🔗 Graph
- 부모: [[Hash-Functions-and-Maps]] · [[Approximate-Nearest-Neighbor]]
- 변형: [[MinHash]] · [[SimHash]] · [[Cross-Polytope-LSH]]
- 응용: [[Near-Duplicate-Detection]] · [[Vector-Database]] · [[Streaming-Dedup]]
- Adjacent: [[HNSW]] · [[Product-Quantization]] · [[Bloom-Filters in Search]]
## 🤖 LLM 활용
**언제**: Billion-scale dedup, Jaccard-based near-dup detection, streaming pipeline.
**언제 X**: High-recall ANN with dense embeddings (use HNSW/IVF-PQ).
## ❌ 안티패턴
- **단일 hash table**: recall 낮음 — 매 L tables 필수.
- **k 너무 큼**: false neg 폭증.
- **Dense embedding에 MinHash**: 매 잘못된 family 선택.
## 🧪 검증 / 중복
- Verified (Indyk & Motwani 1998; Mining of Massive Datasets ch.3).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — LSH families + datasketch/FAISS examples |