How socket.io-redis adapter works? 레디스 어댑터 동작원리

보통 실시간 메시징 처리에 socket.io와 redis를 많이 사용하는데, 그 동작 메커니즘이 자세히 소개된 글을 찾기 어려웠다. 이유는 간단한데, 소스코드가 그냥 간단해서 글로 쓰고 자시고 건더기도 없어 그런듯. 

기본적으로 socket.io는 Server, Namespace, Room, 그리고 Socket으로 구성되어있고 멀티 노드를 위해 pluggable 디자인 방식으로 Adapter라는 것이 존재한다. 

Default In-Memory 방식은 배열에 socket과 room 정보를 저장하기 때문에 웹 서버에 붙어있는 clients 외 에는 알 길이 없다. 이때 redis adapter를 사용하면 다음과 같이 동작하는데, sender가 원격에서 넘어왔다면 그냥 내 로컬 clients에게 deliver하는 것으로 종료하고 그렇지 않으면, 다른 노드에게 publish하여 메시지를 전달한다. 


분산 인프라 치고는 놀랍게도 Javascript 몇 줄 안되는 소스코드로 node, socket.io, 그리고 redis가 동작한다. 좀 이해하기 쉽게 도식화하면 다음과 같다:


딥 러닝의 블랙 박스 열어보기

Opening the black box of Deep Neural Networks via Information
- https://arxiv.org/pdf/1703.00810.pdf

지금까지 딥 러닝은 어떻게 동작하는지 이해할 수 없다고 믿어져왔다. 그러나, 천재들은 그 근본 원리를 이해하려고 노력하고 있지.

이 논문은 SGD가 무슨 역할을 하는지에 대한 해석으로, 이들은 SGD가 drift와 diffusion단계로 구분된다고 설명한다.

첫 drift 단계에서는 multidimensional space를 탐험하고, 수렴을 시작하면 diffusion 단계로 접어들어 (첨부 그림에서 점선 오른쪽에 해당) 굉장히 느려지기 시작하며 chaotic 한 단계로 들어가는데 이게 바로 네트워크가 압축하는 법을 배우는 과정이라는 것이다.



SGD의 무질서도는 local minima에 빠지지 않고 더 나은 방향으로 수렴 할 가능성을 제공 할 뿐만 아니라, diffusion 단계에서 매우 효과적인 internal representations(?)를 생성하는데 자기가 볼쩍에 다소 과한것으로 보이며, 자기들의 IB iterations with stochastic relaxation methods로 DNN 학습 방법을 개선할 수 있을거라고 얘기한다.

제프리 힌트 교수가 지대한 관심과 찬사를 보냈기에 많은 관심을 받고 있는 내용인데, 딥 러닝 대가들의 근본 원리와 최적화 이론에 대한 얘기라, 나는 훔쳐만 봤지 뭔소리인지는 정확히는 이해하기 어렵다.

THE HUNT (JAGTEN)


The Hunt (2012 film).jpg추측으로 만들어진 억측 또는 소문을 ‘카더라 통신’이라고 한다. ‘누가 언제 어쨌다 카더라.’로 시작되는 이야기. 믿거나 말거나 장난처럼 흘린 말이 시간이 지나면서 엉뚱한 방향으로 튀어 종잡을 수 없게 된다. 급기야 열기구처럼 둥둥 떠다니며 온갖 티를 묻히기도 하는데, 그 볼썽사나움이란 형언하기조차 어렵다.

요즈음에는 ‘넷카시즘’이 횡행한다. 인터넷이나 SNS 공간에서 누리꾼 다수가 특정 개인을 공격하는 것 말이다. 마녀사냥이라고 해야 할지. 광속도로 자행되는 돌팔매질 앞에서 당하는 사람은 속수무책이다.

둘의 공통점은 불특정 다수가 특정 개인을 잡도리한다는 것이다. 자신과 이해관계가 없음에도, 심지어 상대를 잘 알지 못함에도 덩달아 가담하여 사태를 악화시킨다. 

‘거짓 동의 효과’라는 게 있다. ‘다른 사람이 나와 같을 것으로 생각하는 경향으로 그들에게 자신을 투영하는 현상.’을 말하는 것인데, 집단적 왜곡으로 치달을 때 그 파괴력은 상상을 초월한다. 속된 표현으로 사람 잡을 일이다. 

잠시 우리 직장으로 고개를 돌려보자. 지금 우리는 어느 동료직원에게 돌을 던지고 있지 않은가. 어떤가. 부지불식중에 확인되지 않은 남 이야기를 하고 있지 않느냐 말이다.

이러한 상황에 내몰린다면 어떻게 처신해야할까? 편히 앉아 영화 한편 때리셔라. The Hunt.

페이스북, AI의 직관적 물리학 체계 실험

아들을 데리고 탄천을 산책 하면서 우연히 돌계단을 오르며 생각했다. 표면이 고르지 않은 돌계단에 나는 내딛을 위치를 어떻게 결정하고 있는가?

우리의 뇌는 직관적 지름길과 어림법heuristic을 많이 가지고 있다. 예를 들면, 움직이는 물체의 궤적을 예측할 수 있는 "직관적 물리학 체계"를 타고 난다. 연구에 따르면, 신생아도 자신에게 다가오는 물체가 충돌 궤적을 따르느냐 아니냐에 따라 상이한 반응을 보인다.

우리는 '던져진 물체와 '낙하하는' 물체를 직관적으로 구분한다. 던져진 물체에 대해서는 물체에 가해진 힘과 중력 두 가지를 고려하지만 낙하하는 물체에 대해서는 중력만 고려되기 때문에 그 물체는 곧게 하강할 것이라 예측하는 것이다.

완전한 3차원 재구성을 하지 않아도 단순한 사진 장면에 대해 우리는 물리적으로 이해할 수 있고, 이것을 직관적 물리학 체계라고 할 수 있다.


최근 INRIA와 Facebook AI 팀의 연구원들은 AI가 이러한 직관적 물리학을 얼마나 이해하는지 진단하는 평가 프레임 워크를 개발했다. (참고: IntPhys: A Framework and Benchmark for Visual Intuitive Physics Reasoning)

만일 AI가 이러한 직관적 물리학 체계를 얻게 된다면 바둑 두는 정도가 아니라 생각된다. 씹~소오름.

Introducing Rebase: a Firebase like backend service based on Node.js, Redis, and HBase

삼성전자 재직시절 (아마도 2 ~ 3년 전) 대외 기고 승인까지 다 받아놓고 게재하지 않았던 글을 이제서야 올려본다. 지금 다시 보니 감회가 새롭네.

Introducing Rebase: a Firebase like backend service based on Node.js, Redis, and HBase 

Guest post written by Edward J. Yoon and Sungwon Han, Senior Software Engineers, Samsung Electronics.

 Event-driven applications that handle user actions, sensor outputs, or messages from other applications have become increasingly popular in recent years, in part as a result of the proliferation of smart devices and the Internet of Things. With this, the real-time databases (like Google's Firebase [1] and RethinkDB [2]) are considered as important technologies for supporting these non-traditional applications and workloads. In this guest post, we introduce Rebase, a Firebase-like backend service that allows you to store and synchronize data in online/offline modes, push notifications and provides analytics (in near future) for mobile platforms. Rebase was first deployed to run on Amazon AWS. However due to performance and cost reasons, we soon migrated it to run on Joyent’s Triton Cloud. We share performance benchmarks for Rebase on Joyent Triton vs. Amazon AWS, which served as our key decision metric.

Rebase 

Recently, we developed a container-based real-time database for Samsung IoT applications, called Rebase. It uses event-driven model to notify changes among clients, stores data as JSON objects in a K/V databases. It also provides easy-to-use RESTful APIs and client libraries that accessible to cross-platforms such as iOS and Android in form of SDKs. With Rebase, developers can focus on core functionality and not have to worry about the infrastructure running the backend services.

Below is a reference architecture for Rebase. It has the following key components:

 Rebase backend container stack 

NGINX, Node.js, and Standalone Redis 

We adopted NginX, Node.js, and Redis as a backend servers. Node.js is a JavaScript runtime environment that processes incoming requests asynchronously in a loop, called event loop. It has an event-driven and non-blocking I/O model, thus it allows handling large throughput of data and building scalable applications. NginX is used as a load balancer, and the standalone Redis is used for message queueing and asynchronous messaging.

Redis and HBase Cluster 

For the persistent storage, we reviewed NoSQLs and K/V stores such as Redis, HBase, and MongoDB. MongoDB isn't suitable for the time-series workloads. Redis is very fast but it has limited scalability and persistency capabilities. HBase is column-oriented K/V store that allows horizontal scalability, and allows to store not only JSON object itself but also parsed columns for fast columnar scan. So, we decided to use the sharded Redis cluster as cache storage, and the HBase as persistent storage.

Programming Interface 

Rebase's client SDK is very similar to the Google's Firebase. It provides basic CRUD operations and stream subscriptions APIs. For example, chatting app synchronization can be written like the following:
var setMessage = function(data) {
    var val = data.val();
    this.displayMessage(data.key, val.name, val.text);
  }.bind(this);

// Loads the last 3 messages and listen for new ones.
this.messages.limitToLast(3).on('child_added', setMessage);

Joyent Triton vs. AWS 

Cost

In the early days of Rebase, we mainly used Amazon EC2 instances and ECS service as a container pools for Rebase backend service. AWS served our needs well, when our users and traffic workloads were small. However as we started scaling out, it quickly turned into a very expensive option for our long term needs.

Server Density

Additionally, AWS runs containers on VMs, which adds unnecessary overhead to the compute nodes. Also if you end up running Kubernetes to manage containers, on VMs running on EC2, the layers of abstraction keep adding flab and reduce efficiency of the compute resources. We tried Joyent and were impressed with it’s containers on bare-metal service. No VMs or abstraction layers to go through.

Performance

Moving to bare metal with Joyent's Triton service [3], we were able to get significant performance improvements as following throughput graph illustrates. For Read operations, we were able to increase throughput by 3~5% while keeping latency under 1 second. For Write operations, we were able to increase throughput by 63% at the same latency of under 1 second. 

Deployment Time

We were able to reduce the deployment time drastically (5 minutes to 1 minute) for new cluster of rebase backend service using Triton’s optimized container provisioning.

State of the Project 

We are still in the early stages and the code isn't meant for production usage yet. The auto-scaling with minimal downtime is challenging. An elastic solution that allows auto scaling up and down or non-stop migrating service is our next goal. Container Pilot and the auto pilot pattern look like some of the right tools to try.

We also plan to open source this project once we've made a few more refinements to it, so that we could tailor it and contribute back to the wider community. We will also be looking to add contributors, so keep a lookout on here for updates! 

References

1. "Google Firebase". https://firebase.google.com/
2. "RethinkDB". http://www.rethinkdb.com/
3. "Joyent Triton". https://www.joyent.com/triton

Holonomic brain theory and Capsule Network

Hinton's CapsNet explains about entity's pose, lighting and deformation, instead of shape feature and pattern. While I reading Hinton's idea, I thought about Holonomic brain theory.

"If a holographic image, containing the image of an apple, is cut in half and then illuminated by a laser, each half will contain the overall image of the apple! Even if the halves are sliced again and again, from each little piece of the film can be restored the image of a whole apple (although the image will become less clear with the reduction of the parts)."

Our brain is also very similar. We don't store images in brain, we store some transformed code. We don't lose our memory, it just fade out.

Gear Watchface Designer on Mac OS X

재직 시절에 (싸게) 구매했던 기어 S3를 쓰다보면 watchface 권태기를 3개월마다 겪게 되는데, 그럴때마다 구매한게 지금 거진 20개 가까이 된다. 그런데 내 마음에 썩 들지도 않고 얼마 안하지만 아깝기도 해서 직접 만들어보기로 했다.

디자이너들을 위한 개발 도구는 Gear Watchface Designer를 검색해서 설치하면 되는데, Java 버전에 따라 키보드와 마우스가 먹통이 되는 현상이 있다. Java다 보니 뭐 맥북이든 윈도우즈든 상관은 없고, 최신버전 JDK에서는 동작하지 않고 반드시 JDK 8u151 [1] 버전을 설치해야 한다. 이것 때문에 개삽...

아래는 내가 지금 만들고 있는 watchface 인데, free 이미지를 활용해서 Roman 스타일로 내 맘에 꼭 든다 ㅋ 돈 받고 팔아봐야지~


Elegant Roman Javik 검색하면 나옴~


[1]. JDK 8u151 버전 설치 링크: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-javase8-2177648.html?printOnly=1

Storm vs. Spark Streaming: 내부 메커니즘의 차이점

트렌드 면에서는 기계학습에 밀린 것 같지만, 실시간 처리 또는 스트리밍 처리는 대단히 중요한 기술이다. 오픈소스로 존재하는 Storm과 Spark을 한번 비교해보자. 물론 솔루션 선택은 자유이고, 상황에 맞는 것이 바로 최적의 솔루션이다.

1. Task Prallel vs. Data Parallel

계산 프로그래밍 모델에서부터 느낄 수 있는 가장 뚜렷한 차이는 먼저, Storm은 Task Parallelism이고 Spark Streaming은 Data Parallelism이다.  개인적으로는 보다 완성도 높은 시스템을 구현할 수 있는 Storm의 계산 그래프 구조를 선호하지만 코드의 복잡도 면에서는 Spark이 유리할 수 있다.

2. Streaming vs. Micro-batches

Spark streaming의 경우는 엄밀히 말하면 실시간 처리보다는 작은 단위의 배치 연속이라고 할 수 있다. Storm은 전형적인 event-driven record at a time processing model로써 살아있는 데이터를 처리한다고 하면, Spark은 휴면 상태로 넘어간 데이터를 처리한다. 때문에 Latency에서 차이가 발생하는데 Storm은 subsecond, Spark의 경우에는 사용자 임의지정 few seconds가 된다.

여기에서 중대한 차이점이 발생하는데, Storm의 경우에는 데이터 유실이 없어야 할 때 (no data loss), Spark은 중복 연산이 없어야할 때 (exactly once) 선택하는 것이 좋다.

한편, Storm Trident는 Micro-batches 스타일도 가능하다고 한다.



3. Stateless vs. Stateful

앞서 소개한대로 Storm은 매 레코드 별로 처리하기 때문에 State을 유지하지 않기 때문에 장애 복구 메커니즘이 Spark보다 복잡하고 re-launching 시간이 더 걸릴 것이다.  Stateless vs. Stateful는 (뭔가 더 있을 것 같지만) 장애 복구 외의 차이점은 전혀 없다.

4. Integration with Batch processing

긴말 필요없이 당연히 Spark이 유리하겠다.

여기까지 알아봤고 과연 무엇이 최상의 솔루션인가? 내 생각엔 Storm이 조금 우수하다 판단한다. 물론 최적의 솔루션은 당신 상황에 맞아야 하겠다.

Belief Propagation 알고리즘

한 때, 병렬 그래프 연산과 알고리즘에 심취한 적이 있다. 그중에 신뢰 전파(Belief Propagation) 알고리즘에 대해 적어본다. 이 알고리즘은 Graphical model에서 inference problem의 근사해를 추정하는 기법으로, Graph 상에 관측된 특정한 확률변수의 분포가 주어졌을 때, 직간접적으로 영향 받는 모든 관측되지 않은 확률 변수의  Marginal distribution을 추정하는 기법이다.

즉, 아래와 같은 Poly Tree 구조 안에 C 노드와 E 노드가 Evidence가 주어졌을 때, \( P(B|C,E) = ? \)



알고리즘은 각 노드 간 Down or Upward Message Passing과 Data Fusion 단계를 거쳐 각 노드의 확률 분포를 추정하기 때문에 병렬 연산을 위해서 Bulk Synchronous Parallel 모델이 대단히 적합하다 할 수 있다.

문득, Google의 DistBelief는 이러한 분산 베이지안 네트워크의 메시지 전달 방식이라 지어진게 아닌가 싶다. 그나저나 요즘의 나는 트리 탐색 구현 정도나 할 수 있을까 모르겠네?

딥 러닝의 비밀을 파헤치는 새로운 이론

예루살렘 히브리 대학 (Hebrew University of Jerusalem)의 컴퓨터 과학자이자 물리학 교수인 티쉬비(Naftali Tishby)가 작년 베를린의 한 컨퍼런스에서 딥 러닝이 어떻게 작동 하는지를 설명하는 새로운 이론을 제시했다.

"deep learning is an information bottleneck procedure that compresses noisy data as much as possible while preserving information about what the data represent."

딥 러닝이란, 데이터의 노이즈는 줄이고 그것이 무엇을 표현 하는지에 대한 주요 정보만 남기는 정보 병목 (Information bottleneck) 절차라는 것이다.

정보 병목 기법 (Information bottleneck method) 은 두 랜덤변수의 결합확률분포가 주어진 경우, 두 변수 간의 상호 정보량을 최대한 보존하면서 한 변수를 압축하는 기법이다 (위키 참고 [1]).

위키에 Information theory of deep learning 섹션은 정리되다 말았지만, X가 실제 개 사진의 픽셀같은 복잡한 대량의 데이터 셋이고, Y가 “개”와 같이 그 데이터를 표현하는 단순한 변수라 가정해보자. 딥 러닝은 즉, Y의 정보를 최대한으로 보유하고 있는 X 의 축약된 표현을 구함으로써 일반화라는 목표에 도달하는 과정이라는 것이다.

내가 이 내용에 관심을 갖게 된 이유는, 딥 러닝 대부인 힌튼 교수께서 친히 티쉬비의 연구 결과에 찬사를 보냈다고 한다.

 “I have to listen to it another 10,000 times to really understand it, but it's very rare nowadays to hear a talk with a really original idea in it that may be the answer to a really major puzzle.”

한편으로 또한 재밌는 것은, 티쉬비 교수 인터뷰에 따르면 딥 러닝이 잘 할 수 있는 것과 못하는 것의 한계는 명백 해진다. 세부적인걸 포기하기 때문에 큰 수 곱셈이나 암호 코드 박살 내는건 잘 해내지 못할 거라고 한다 ㅋ.

우리 인간은 보고싶은 것만 본다. 세계로부터 전달되는 엄청난 정보의 대부분을 포기하고 정말로 보고 싶은 것만 보고 있는지 모르겠다.

1. https://en.wikipedia.org/wiki/Information_bottleneck_method


에이전트 오브 쉴드 엉뚱 짤막 후기

전형적인 미드 중 하나로 .. 뭔가 스파이 비밀조직에서 팀을 이루고 문제를 해결해나가는 스토리다. 한국은 누구랑 친해? 또는 누구랑 놀지마, 친하게 지내, 그리고 경쟁적이고 아파트 평수로 파를 가르는 문화가 있는데 아이를 키우는 입장에서 정말 부럽다는 생각이 든다. 다양성을 인정하고 팀으로 문제를 해결하는 환경으로 바뀌어나갔으면 좋겠어.