Skip to main content

DNA-inspired memory SDK for AI cognitive computing

Project description

CPUT DNA Memory SDK

基于物理公理构建的生物启发式持久记忆引擎

v0.1.0 · CPUT理论框架 · Apache 2.0

安装 · 快速开始 · API文档 · 架构设计 · 性能基准


这是什么?

DNA Memory SDK 是一个从第一原理物理公理推导出的记忆系统,将信息编码为自描述的DNA序列。

不同于传统的向量数据库或键值存储:

特性 向量数据库 键值存储 DNA Memory SDK
编码方式 浮点向量 字符串→值 4bp碱基序列
信息密度 低(128-1536维) 中等 每节点仅4bp
结构 扁平 扁平 树状层级 + DNA双链
遗忘机制 TTL过期 甲基化衰减 + 睡眠巩固
可解释性 黑箱 透明 完全可审计(从公理推导)
生物兼容 FASTA导出 / GC含量 / 互补配对

核心概念

┌──────────────────────────────────────────────────────────────┐
│                    DNA Memory SDK 架构                        │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│  ┌─────────────┐   encode()   ┌──────────────────────────┐  │
│  │ (d1,d2,d3,  │──────────────▶│ 自描述DNA片段             │  │
│  │  label)     │              │ ┌────┬────┬─────┬────┐   │  │
│  │             │              │ │ T11│ ID │内容 │ T11│   │  │
│  └─────────────┘              │ └────┴────┴─────┴────┘   │  │
│                                └──────────────────────────┘  │
│                                         │                    │
│  ┌─────────────────────────────────────────────────────┐    │
│  │              GrowableDNAMemory                       │    │
│  │  ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌──────────────┐ │    │
│  │  │write│ │read │ │search│ │decay│ │sleep_consolid│ │    │
│  │  └─────┘ └─────┘ └─────┘ └─────┘ └──────────────┘ │    │
│  │                                                      │    │
│  │  树状结构:    [1] 根记忆                              │    │
│  │               ├── [2] 子记忆A  met=████░ 0.80        │    │
│  │               ├── [3] 子记忆B  met=██░░░ 0.40        │    │
│  │               └── [4] 子记忆C  met=░░░░░ 0.05 → 衰减  │    │
│  └─────────────────────────────────────────────────────┘    │
│                           │                                  │
│  ┌─────────────────────────────────────────────────────┐    │
│  │              DNACoupling (可选)                      │    │
│  │                                                      │    │
│  │  正向: Agent状态 ──record_state()──▶ DNA记忆         │    │
│  │  反向: DNA记忆   ──get_modulation()──▶ 调制信号      │    │
│  │  闭环: 行为结果  ──update_association()──▶ 强化/弱化  │    │
│  └─────────────────────────────────────────────────────┘    │
│                                                              │
└──────────────────────────────────────────────────────────────┘

安装

pip install dna-memory

或从源码安装:

git clone https://github.com/hbfbee-sys/dna-memory.git
cd cput-sdk
pip install -e .

快速开始

基础用法

from dna_memory import GrowableDNAMemory

# 创建记忆系统
mem = GrowableDNAMemory()

# 写入记忆 — 每条记忆由节点组成
# 节点格式: (d1, d2, d3, label), 其中 d1/d2/d3 ∈ {0,1,2,3}
seg_id = mem.write(
    title='学习Transformer架构',
    nodes_data=[
        (1, 2, 3, 'Self-Attention'),
        (0, 3, 1, 'Multi-Head'),
        (2, 1, 0, 'Position-Encoding'),
    ],
    initial_methylation=0.5  # 初始保护度
)

# 读取记忆 — 返回完整解码结果
result, err = mem.read(seg_id)
print(f"标题: {result['title']}")
print(f"DNA链: {result['dna_forward']}")
print(f"节点数: {result['node_count']}")

# 搜索记忆
matches = mem.search('Transformer')

# 查看记忆树
print(mem.list_tree())

# 基因组统计
stats = mem.get_genome_stats()
print(f"基因组: {stats['total_bp']}bp, GC含量: {stats['gc_content']:.1f}%")

树状记忆结构

# 生长子记忆 — 形成层级结构
child_id = mem.grow(
    parent_seg_id=seg_id,
    title='Attention计算细节',
    nodes_data=[
        (1, 1, 1, 'Q=xW_q'),
        (2, 2, 2, 'K=xW_k'),
        (3, 3, 3, 'V=xW_v'),
    ]
)

# 查看树结构
print(mem.list_tree())
# [1] 学习Transformer架构 (3节点, met=██░░░ 0.50)
#   [2] Attention计算细节 (3节点, met=░░░░░ 0.00)

记忆生命周期

import numpy as np

# 强化重要记忆(提高甲基化保护)
mem.reinforce(seg_id, boost=0.3)  # met: 0.5 → 0.8

# 睡眠巩固 — 模拟生物记忆整理
mem.sleep_consolidation('N3')   # 深睡: 强化重要记忆, 弱化无用记忆
mem.sleep_consolidation('REM')  # 梦眠: 随机重组, 创造新关联

# 记忆衰减 — 模拟自然遗忘
for step in range(100, 200):
    mem.apply_decay(current_step=step, decay_rate=0.001)

# 删除记忆
mem.delete(seg_id)  # 删除片段及其所有子片段

持久化

# JSON格式保存/加载
mem.save('my_memories.json')
mem.load('my_memories.json')

# FASTA格式导出(生物信息学兼容)
mem.export_genome_fasta('genome.fasta')
# >seg_1 | 学习Transformer架构 | met=0.800 | 53bp
# TGACTGACTGAACGTGACAGACTGACTGACTGACATCGAT...

与AI Agent集成

from dna_memory import GrowableDNAMemory, DNACoupling

mem = GrowableDNAMemory()
coupling = DNACoupling(mem, snapshot_interval=5)

# === 在你的Agent循环中 ===

for step in range(1000):
    # 1. Agent执行动作
    state = agent.get_state()  # {'confidence': 0.8, 'task': 'planning', ...}
    action = agent.act(state)
    reward = env.step(action)
    
    # 2. 正向: 记录经验到DNA
    coupling.record_state(state, step=step)
    
    # 3. 事件触发记录(不受interval限制)
    if reward > 0.9:
        coupling.record_event('high_reward', {'reward': reward, 'step': step}, step)
    
    # 4. 反向: 从DNA记忆中获取调制信号
    modulation = coupling.get_modulation(state)
    agent.apply_modulation(modulation['modulation_values'])
    
    # 5. 闭环: 更新记忆关联值
    for match in modulation['top_matches']:
        coupling.update_association(match['seg_id'], outcome=reward)
    
    # 6. 周期性衰减
    if step % 50 == 0:
        mem.apply_decay(step)
    
    # 7. 定期睡眠巩固
    if step % 200 == 0:
        mem.sleep_consolidation('N3')
        mem.sleep_consolidation('REM')

API文档

GrowableDNAMemory

方法 参数 返回值 说明
write() title, nodes_data, parent_seg_id?, initial_methylation? int (seg_id) 写入新记忆
read() seg_id (dict, None) 或 (None, str) 读取记忆
grow() parent_seg_id, title, nodes_data int (seg_id) 生长子记忆
update() seg_id, new_nodes_data, new_title? None 更新记忆内容
delete() seg_id bool 删除记忆(含子片段)
search() keyword list[dict] 关键词搜索
reinforce() seg_id, boost? None 甲基化强化
apply_decay() current_step, decay_rate? int (清除数量) 记忆衰减
sleep_consolidation() sleep_stage ('N3'/'REM') dict (统计) 睡眠巩固
get_genome_stats() dict 基因组统计
list_tree() str 树状可视化
save() filepath None 保存为JSON
load() filepath None 从JSON加载
export_genome_fasta() filepath None 导出FASTA

DNACoupling

方法 参数 返回值 说明
record_state() state, step, title?, force? int (seg_id) 记录状态快照
record_event() event_type, data, step, priority? int (seg_id) 记录重要事件
detect_phase_transition() current_phase, step int (seg_id) 检测相态跃迁
get_modulation() current_state dict 获取调制信号
update_association() seg_id, outcome None 更新关联值
set_state_encoder() encoder_fn None 自定义编码器
set_similarity_function() sim_fn None 自定义相似度

编解码函数

from dna_memory import encode_node, decode_node, encode_id, decode_id

# 节点编码: (d1,d2,d3) → 4bp DNA
enc = encode_node(1, 2, 3)
# {'dna_4bp': 'CTAC', 'h_code': 27, 'struct_type': 'S-', ...}

# 节点解码: 4bp DNA → (d1,d2,d3)
dec = decode_node('CTAC')
# {'d1': 1, 'd2': 2, 'd3': 3, 'chirality_valid': True, ...}

# ID编码: int → 8bp DNA
id_dna = encode_id(12345)  # 'GCTAGCTA'

# ID解码: 8bp DNA → int
id_val = decode_id('GCTAGCTA')  # 12345

架构设计

编码体系

每个信息节点 (d1, d2, d3) 通过三层Ring编码映射为4bp DNA序列:

d1 ∈ {0,1,2,3} ──Ring0──▶ b0 ∈ {A,C,T,G}  ← 基础维度
d2 ∈ {0,1,2,3} ──Ring1──▶ b1 ∈ {G,A,C,T}  ← 旋转维度
d3 ∈ {0,1,2,3} ──Ring2──▶ b2 ∈ {C,T,G,A}  ← 拓扑维度
chirality      ──Chiral──▶ b3 ∈ {A,G,C}    ← 手性校验位

64种节点类型 × 手性校验 = 结构化信息编码,支持:

  • 正向链/反向链(Watson-Crick互补配对)
  • 自描述片段(包含ID、父ID、内容、校验和)
  • 11T边界标记(结构性连接器 TGACTGACTGA

记忆生命周期

写入(write) → 甲基化=0.0 → 强化(reinforce) → 甲基化↑
                              ↓
              睡眠巩固 ←── 日常运行 ←── 衰减(decay)
              N3: 强化重要记忆     → 甲基化衰减
              REM: 创造新关联      → 甲基化=0 → 清除

性能基准

测试环境: Python 3.11, Mac Mini M4 Pro

操作 延迟 吞吐量
单片段写入(3节点) 0.18ms 5,500 ops/sec
单片段写入(1节点×100) 0.087ms/op 11,500 ops/sec
片段读取 0.02ms 50,000 ops/sec
片段搜索 0.02ms 50,000 ops/sec
N3深睡巩固 0.04ms 25,000 ops/sec
REM梦眠重组 0.05ms 20,000 ops/sec
1000次批量写入(2节点) 0.17ms/op 5,778 ops/sec

压缩比:

  • 201片段基因组 vs JSON: 1.8:1
  • 白皮书结构化数据 vs JSON: 299:1

使用场景

  1. AI Agent 持久记忆 — Agent跨会话积累经验,不再"失忆"
  2. 边缘设备记忆 — 轻量级,CPU可运行,不依赖GPU
  3. 可解释AI — 从公理到行为全链路可审计
  4. 神经形态计算 — 可与Loihi 2/BrainChip等芯片配合
  5. 认知科学研究 — 可计算的认知理论实现

许可证

Apache 2.0

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

dna_memory_sdk-0.1.0.tar.gz (32.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

dna_memory_sdk-0.1.0-py3-none-any.whl (27.8 kB view details)

Uploaded Python 3

File details

Details for the file dna_memory_sdk-0.1.0.tar.gz.

File metadata

  • Download URL: dna_memory_sdk-0.1.0.tar.gz
  • Upload date:
  • Size: 32.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.13

File hashes

Hashes for dna_memory_sdk-0.1.0.tar.gz
Algorithm Hash digest
SHA256 2ba7552d6e9ef8f5008da6a79e22156f8ebb3cdaf158e9937c3f22ec80396c80
MD5 71933a52831cfd13bed6f9b51d81e8a6
BLAKE2b-256 5fc8974ec52aea88d059ca23debe40bfe6e1f9f33686e48229e2acc898d14609

See more details on using hashes here.

File details

Details for the file dna_memory_sdk-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: dna_memory_sdk-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 27.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.13

File hashes

Hashes for dna_memory_sdk-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b16d81b52d6b97834a6b42945707ca0f51ccf4a0d9f55569030b9e7305ebc676
MD5 30cc9749ef5f80b973ee3b4bc602b4ee
BLAKE2b-256 6570a0682434845d1aa46e633e9fe302b1b9ca6e1842f1073cfb3728bc101750

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page