메뉴
HN
Hacker News 29일 전

신경망과 암호화 알고리즘이 놀라울 정도로 비슷한 이유

IMP
7/10
핵심 요약

언뜻 보기에 전혀 다른 분야인 인공신경망과 대칭키 암호화 알고리즘이, 기저에 깔린 구조와 작동 방식이 매우 유사하다는 흥미로운 분석입니다. 두 분야 모두 순차적 및 병렬적 시퀀스 처리 방식, 선형과 비선형 레이어의 교차 반복, 그리고 행과 열을 교차 혼합(Mixing)하여 성능을 극대화하는 구조를 공유합니다. 이는 두 분야가 서로 아이디어를 베낀 것이 아니라, 약한 정확성 요구사항과 하드웨어 최적화라는 동일한 근본적 문제 해결 과정에서 자연스럽게 수렴 진화했기 때문입니다.

번역된 본문

왜 신경망과 암호문은 그토록 비슷할까요? 언뜻 보기에 언어 모델을 훈련시키는 것과 데이터를 암호화하는 것은 완전히 다른 문제처럼 보입니다. 하나는 패턴을 학습해 텍스트를 생성하고, 다른 하나는 정보를 숨기기 위해 섞는 작업이니까요. 그러나 두 분야의 기저에 있는 알고리즘은 흥미로울 정도로 유사하며, 이는 단순히 한쪽이 아이디어를 따 온 것이 아닙니다.

시퀀스 처리: 순차적(Sequential) 방식 전통적인 순환 신경망(RNN)을 살펴봅시다. 텍스트 토큰을 순환 상태에 토큰 단위로 주입한 후 출력 텍스트를 생성합니다. (인코더-디코더 구조) 이는 SHA-3의 스펀지(Sponge) 구조와 구조적으로 완벽히 동일합니다. 상태에 바이트를 흡수(Absorbing)한 후 해시값을 짜내는(Squeezing) 방식이죠. 가변 길이 입력을 고정 크기 상태로 처리하려면 순차적으로 흡수하는 것이 자연스러운 선택이기에 이 유사성은 그리 놀랍지 않을 수 있습니다.

시퀀스 처리: 병렬(Parallel) 방식 현대 하드웨어는 병렬 처리에 최적화되어 있어 순차적 흡수 방식은 성능을 낭비합니다. 두 분야 모두 동일한 해결책을 찾았습니다. 순차적으로 실행하는 대신 비용이 많이 드는 함수 f를 모든 청크에 병렬로 실행한 뒤 단순한 덧셈으로 결합하는 것입니다. 단순한 덧셈만으로는 순서 정보가 사라지기 때문에, 두 접근 방식 모두 각 청크에 '위치 인코딩(Positional Encoding)'을 추가하여 순서를 복원합니다. 신경망에서 이 구조는 순차적 RNN을 개선한 트랜스포머(Transformer) 아키텍처를 구동합니다. 암호학에서는 가장 빠른 메시지 인증 코드(MAC)를 구동합니다.

기본 원시 구조: 동일하게 반복되는 선형 및 비선형 레이어의 교차 가변 길이 처리를 제거해 봅시다. 핵심 함수 내부에는 무엇이 있을까요? 두 분야 모두 동일한 패턴을 보입니다. '선형 변환 - 비선형 변환 - 반복'입니다. 선형 변환은 서로 다른 벡터 위치 사이에서 '혼합(Mixing)'을 제공하여 많은 벡터 요소가 다른 많은 요소에 영향을 미치게 합니다. 비선형 변환은 복잡성을 제공합니다. 비선형 변환이 없다면 레이어 스택 전체가 단일 선형 변환으로 퇴화해 버릴 것입니다. 두 분야 모두 맞춤형 구조를 만드는 대신 이 '동일한 레이어'를 여러 번 반복합니다. 이를 통해 연구 및 엔지니어링 노력을 집중시킬 수 있습니다. 즉, 분석하고 소프트웨어나 실리콘(하드웨어)에 최적화해야 할 레이어 유형이 단 하나뿐이게 됩니다.

효율적인 혼합: 행과 열의 교차 더 자세히 들여다봅시다. 두 분야 모두 상태를 그리드(Grid)로 구성하고 행(Row)을 혼합하는 것과 열(Column)을 혼합하는 것을 번갈아 가며 수행합니다. 신경망에서는 어텐션(Attention)이 시퀀스 위치(행) 전체를 혼합하고, 피드포워드(Feed-forward) 레이어가 각 위치(열) 내부를 혼합합니다. AES 암호에서는 ShiftRows가 열 전체에 걸쳐 순열을 수행하고 MixColumns가 그 내부를 결합합니다. ChaCha20 암호는 행 단위와 대각선 혼합을 번갈아 수행합니다. 이러한 분해된(Factored) 접근 방식은 전체 상태를 한 번에 혼합하는 것보다 종종 더 나은 성능을 보여줍니다. 혼합 단계가 선형보다 느릴 경우 점근적으로 더 빠른 경우가 많습니다. 예를 들어, 이차(Quadratic) 혼합 하에서 크기가 m인 n개의 행을 혼합하는 비용은 전체 행렬을 처리할 때의 O(n²m²)에 비해 O(nm²)입니다. 더 중요한 점은 각 행이 독립적으로 처리되고 작업 세트(Working set) 크기가 작아 더 많은 병렬성을 제공하고 캐시 및 레지스터에 더 잘 맞는다는 것입니다.

이러한 유사성을 만들어낸 원인은 무엇일까요? 이러한 유사성은 피상적인 아이디어 복사로 보이지 않습니다. 두 분야의 연구 논문과 역사를 살펴보면 분야 간에 아이디어를 복사한 흔적이 많지 않습니다. 오히려 문제 정의 자체에 근본적인 유사성이 존재하기 때문입니다. 신경망과 대칭키 암호학을 다른 알고리즘 설계 분야와 구분 짓는 것은 다음과 같은 세 가지 속성입니다.

  1. 알고리즘에 요구되는 '정확성(Correctness) 속성'이 놀랍도록 약합니다. 대부분의 알고리즘은 강력한 정확성 요구 사항에 직면합니다. 컴파일러는 프로그램의 의미를 보존해야 하고, 데이터베이스는 저장된 내용을 정확히 반환해야 하며, 네트워크 라우터는 패킷을 전달해야 합니다. 이에 비해 암호학은 정보 손실을 피하기 위한 '가역성(Invertibility)'만 필요로 합니다. 신경망 역시 (중략)
원문 보기
원문 보기 (영어)
Why are neural networks and cryptographic ciphers so similar? At first glance, training language models and encrypting data seem like completely different problems: one learns patterns from examples to generate text, the other scrambles information to hide it. Yet their underlying algorithms share a curious resemblance, and it’s not for lack of creativity. Sequence processing: the sequential version Consider the venerable recurrent neural network , feeding text token by token into a recurrent state before generating the output text: f in 0 in 1 in n <S> out 0 out m out 0 out 1 <E> encoder decoder This is structurally identical to the Sponge construction in SHA-3 , absorbing bytes into a state before squeezing out the hash: f in 0 in n out 0 out m absorbing squeezing rate capacity Perhaps this similarity isn’t surprising: to process variable-length input into a fixed-size state, absorbing sequentially is a natural choice. Sequence processing: the parallel version Modern hardware is parallel all the way down, so sequential absorbing wastes performance. Both fields found the same solution: run the expensive function f f f on all chunks in parallel rather than sequentially, then combine with simple addition: f 0 in 0 1 in 1 n in n out Addition loses ordering information, so both approaches recover ordering by adding position encodings to each chunk. In neural networks, this construction 1 drives the Transformer architecture , which improved upon sequential recurrent networks. In cryptography, this construction powers the fastest Message Authentication Codes 2 . The basic primitive: alternating linear and nonlinear layers, repeated identically Strip away the variable-length processing. What’s inside the core function? The same pattern in both fields: linear transform, nonlinear transform, repeat: Nonlinear Linear Linear transforms provide “mixing” between different vector positions, allowing many vector elements to influence many other vector elements. Nonlinear transforms provide complexity: without them, the whole stack of layers would degenerate to a single linear transform. Both fields repeat this identical layer many times rather than crafting bespoke structures. This focuses research and engineering effort: one layer type to analyze, and to optimize in software or in silicon. Efficient mixing: alternating rows and columns Zoom in further. Both fields organize their state as a grid and alternate between mixing rows and mixing columns: MixColumn MixRow In neural nets: attention mixes across sequence positions (rows), while feed-forward layers mix within each position (columns). In the AES cipher: ShiftRows permutes across columns while MixColumns combines within them. The ChaCha20 cipher alternates row-wise and diagonal mixing. This factored approach often beats mixing the entire state at once. It’s often asymptotically faster if the mixing step is slower than linear: e.g. under quadratic mixing, mixing n n n rows of size m m m costs O ( n m 2 ) O(nm^2) O ( n m 2 ) versus O ( n 2 m 2 ) O(n^2m^2) O ( n 2 m 2 ) for the full matrix. More importantly, each row processes independently and with a small working set size, offering more parallelism and fitting better in caches and registers. What’s causing the similarities? The similarities do not appear to be due to shallow copying of ideas: the research papers and histories of the fields do not reveal much copying between the fields. Instead, there are some underlying similarities between the problem statements. What distinguishes neural networks and symmetric cryptography from other fields of algorithm design are the following three properties. 1. The correctness property demanded of the algorithm is remarkably weak Most algorithms face strong correctness requirements. Compilers must preserve program meaning. Databases must return exactly what was stored. Network routers must deliver the packet. In comparison, cryptography just needs invertibility, to avoid information loss. Neural networks need just differentiability, for gradient descent. You can build a wide range of invertible or differentiable functions simply by composing smaller invertible or differentiable functions. This freedom enables radical simplicity. Both fields build from two or three simple primitives repeated in a loop: simple enough to implement in 20 lines of code. This freedom also enables rapid experimentation: 50+ SHA-3 submissions, hundreds of attention variants. When almost any function could “work”, you can optimize your other goals more aggressively. 2. Quality requirements focus on complexity and mixing More than the basic correctness requirement, both fields share a similar notion of quality. Cryptography needs every output bit to depend on every input bit in complicated ways. Neural networks need the outputs to make the best use of all input information. Both of these reward designs that allow every part of the state to interact with every other part of the state, over and over again. Hence the repeated mixing layers: information must flow between positions not once but many times, creating rich interdependencies. Other fields value mixing but not complexity: sorting requires every output to be compared to every input; network topologies such as Clos networks require every output to be reachable from every input. These fields tend to produce algorithms that interact all inputs with each other exactly once and then finish, whereas cryptography and neural networks repeat the interaction many times. 3. Unusually large emphasis on performance These fields are rare among algorithmic fields in the emphasis placed on low-level hardware performance, routinely including assembly implementations and custom hardware. This emphasis arises from economic pressures such as the ubiquity of encryption and the massive scale of neural networks. Emphasizing performance rewards simple algorithms: it makes assembly implementations or custom hardware tractable. Emphasizing performance also rewards parallelism that we saw at every level of the design: parallel sequence processing at the top level, parallel mixers like alternating row/columns at the middle level, and linear algebra—which is easy parallelizable—at the lowest level. Convergent evolution in algorithms These parallels suggest something fundamental: when we demand algorithms that mix thoroughly and in a complex way, have few other correctness requirements, and perform extremely well on hardware, the best solutions may look very similar. Just as biological evolution independently invented eyes multiple times, human research seems to have invented the “deeply parallel repeated-layer mixers” structure multiple times. We’ve already seen ideas jump between fields. RevNets brought cryptography’s Feistel networks to neural networks, enabling reversible layers that save memory. What’s next? Are there neural network analogs of Column Parity Mixers or “unaligned mixers” ? Or rather, the same construction repeated n n n times, once for each output chunk. ↩︎ Protected Counter Sum and Farfalle use exactly this construction. Even polynomial MACs like GMAC and Poly1305 follow this pattern if you squint, encoding position i i i as the monomial k i k^i k i . ↩︎