Reframing OpenCog Action Selection: Contextual Bandit Problems and Reinforcement Learning

I thought a bit today about how OpenCog’s action selector (based on the Psi model from Dietrich Dorner and Joscha Bach) relates to approaches to action selection and behavior learning one sees in the reinforcement learning literature.

After some musing, I came to the conclusion that this may be another area where it could make sense to insert a deep neural network inside OpenCog, for carrying out particular functions.

I note that Itamar Arel and others have proposed neural net based AGI architectures in which deep neural nets for perception, action and reinforcement are coupled together.   In OpenCog, one could use deep neural nets for perception, action and reinforcement; but, these networks would all be interfaced via the Atomspace, and in this way would be interfaced with symbolic algorithms such as probabilistic logical inference, hypergraph pattern mining and concept blending, as well as with each other.

One interesting meta-point regarding these musings is that they don’t imply any huge design changes to the OpenCog “OpenPsi” action selector.   Rather, one could implement deep neural net policies for action selection, learned via reinforcement learning algorithms, as a new strategy within the current action selection framework.   This speaks well of the flexible conceptual architecture of OpenPsi.

Action Selection as a Contextual Bandit Problem

For links to fill you in on OpenCog’s current action selection paradigm and code, start here.

The observation I want to make in this blog post is basically that: The problem of action selection in OpenCog (as described at the above link and the others it points to) is an example of the “contextual bandit problem” (CBP).

In the case where more than one action can be chosen concurrently, we have a variation of the contextual bandit problem that has been called “slates” (see the end of this presentation).

So basically the problem is: We have a current context, and we have a goal (or several), and we have bunch of alternative actions.  We want in the long run to choose actions that will maximize goal achievement.  But we don’t know the expected payoff of each possible action.  So we need to make a probabilistic, context-dependent choice of which action to do; and we need to balance exploration and exploitation appropriately, to maximize long-term gain.   (Goals themselves are part of the OpenCog self-organizing system and may get modified as learning progresses and as a result of which actions are chosen, but we won’t deal with that part of the feedback tangle here.)

Psi and MicroPsi and OpenPsi formulate this problem in a certain way.   Contextual bandit problems represent an alternate formulation of basically the same problem.

Some simple algorithms for contextual bandit problems are here and a more interesting neural net based approach is here.   A deep neural net approach for a closely related problem is here.

CBP and OpenPsi

These approaches and ideas can be incorporated into OpenCog’s Psi based action selector, though this would involve using Psi a little differently than we are now.

A “policy” in the CBP context is a function mapping the current context into a set of weightings on implications of the form (Procedure ⇒ Goal).

Most of the time in the reinforcement literature a single goal is considered, whereas in Psi/OpenCog one considers multiple goals; but that’s not an obstacle to useing RL ideas in OpenCog.   One can use RL to figure out procedures likely to lead to fulfillment of an individual goal; or one can apply RL to synthetic goals defined as weighted averages of system goals.

What we have in OpenPsi are implications of the form (Context & Procedure ⇒ Goal) — obviously just a different way of doing what RL is doing…

That is:

  • In RL one lists Contexts, and for each Context one has a set of (Procedure ⇒ Goal) pairs
  • In Psi one lists (Context & Procedure ⇒ Goal) triples (“Psi implications”)

and these two options are obviously logically equivalent.

A policy, in the above sense, could be used to generate a bunch of Psi implications with appropriate weights.   In general a policy may be considered as a concise expression of a large set of Psi implications.

In CBP learning what we have is, often, a set of competing policies (e.g. competing linear functions, or competing neural networks), each of which provides its own mapping from contexts into (Procedure⇒ Goal) implications.   So, if doing action selection in this approach: To generate an action, one would first choose a policy, and then use that policy to generate weighted (Context & Procedure ⇒ Goal) implications [where the Context was very concrete, being simply the current situation], and then use the weights on these implications to choose an action.

In OpenCog verbiage, each policy could in fact be considered a context, so we could have

    ConceptNode “policy_5”

and one would then do action selection using the weighting for the current policy.

If, for instance, a policy were a neural network, it could be wrapped up in a GroundedSchemaNode.    A neural net learning algorithm could then be used to manage an ensemble of policies (corresponding behind the scenes to neural networks), and experiment with these policies for action selection.

This does not contradict the use of PLN to learn Psi implications.   PLN would most naturally be used to learn Psi implications with abstract Contexts; whereas in the RL approach, the abstraction goes into the policy, and the policy generates Psi implications that have very specific Contexts.   Both approaches are valid.

In general, the policy-learning-based approach may often be better when the Context consists of a large number of different factors, with fuzzy degrees of relevance.  In this case learning a neural net mapping these contextual factors into weightings across Psi implications may be effective.   On the other hand, when the context consists of a complex, abstract combination of a smaller number of factors, a logical-inference approach to synthesizing Psi implications may be superior.

It may also be useful, sometimes, to learn neural nets for CBP policies, and then abstract patterns from these neural nets using pattern  mining; these patterns would then turn into Psi implications with abstract Contexts.

(Somewhat Sketchy) Examples

To make these ideas a little more concrete, let’s very briefly/roughly go through some example situations.

First, consider question-answering.   There may be multiple sources within an OpenCog system, capable of providing an answer to a certain question, e.g.:

  • A hard-wired response, which could be coded into the Atomspace by a human or learned via imitation

  • Fuzzy matcher based QA taking into account the parse and interpretation of the sentence

  • Pattern matcher lookup, if the Atomspace has definite knowledge regarding the subject of the query

  • PLN reasoning

The weight to be given to each method’s, in each case, needs to be determined  adaptively based on the question and the context.

A “policy” in this case would map some set of features associated with the question and the context, into a weight vector across the various response sources.

A question is what is the right way to quantify the “context” in a question-answering case.  The most obvious approach is to use word-occurrence or bigram-occurrence vectors.  One can also potentially add in, say, extracted RelEx relations or RelEx2Logic relations.

If one has multiple examples of answers provided by the system, and knows which answers were accepted by the questioner and which were not, then this knowledge can be used to drive learning of policies.   Such a policy would tell the system, given a particular question and the words and semantic relationships therein as well as the conversational context, which answer sources to rely on with what probabilities.

A rather different example would be physical movement.   Suppose one has a collection of movement patterns (e.g. “animations” moving parts of a robot body, each of which may have multiple parameters).   In this case one has a slate problem, meaning that one can choose multiple movement patterns at the same time.   Further, one has to specify the parameters of each animation chosen; these are part of the action.   Here a neural network will be very valuable as a policy representation, as one’s policy needs to take in floating-point variables quantifying the context, and output floating-point variables representing the parameters of the chosen animations.   Real-time reinforcement data will be easily forthcoming, thus driving the underlying neural net learning.

(If movement is controlled by a deep neural network, these “animations” may be executed via clamping them in the higher-level nodes of the network, and then allowing the lower-level nodes to self-organize into compatible states, thus driving action.)

Obviously a lot of work and detailed thinking will be required to put these ideas into practice.  However, I thought it might be useful to write this post just to clarify the connections between parts of the RL literature and the cognitive modeling approach used in OpenCog (drawn from Dorner, Bach, Psi, etc.).   Often it happens that the close relationships between two different AI approaches or subfields are overlooked, due to “surface level” issues such as different habitual terminologies or different historical roots.

Potentially, the direction outlined in this post could enable OpenCog to leverage code and insights created in the deep reinforcement learning community; and to enable deep reinforcement neural networks to be used in more general-purpose ways via embedding them in OpenCog’s neural-symbolic framework.

Posted in Uncategorized | 1 Comment

Cogistry: Accelerating Algorithmic Chemistry via Cognitive Synergy

This post describes some speculative ideas for new AI/AGI/Artificial-Life/Artificial-Chemistry development that could be done on top of the OpenCog platform, leveraging OpenCog tools in a novel way.

These are not necessarily proposed for immediate-term development – we have a lot of other stuff going on, and a lot of stuff that’s half-finished or ¾-finished or more, that needs to be wrapped up and improved, etc.   They are, however, proposed as potentially fundamental enhancements to the OpenCog and PrimeAGI (CogPrime) designs in their current form.

The core motivation here is to add more self-organizing creativity to the AGI design.   One can view these ideas as extending what MOSES does in the PrimeAGI design – MOSES (at least in its aspirational version) is artificial evolution enhanced by pattern mining and probabilistic reasoning; whereas Cogistry is, very loosely, more like artificial biochemistry similarly enhanced.

Historical Background

Walter Fontana, in a fascinating 1990 paper, articulated a novel approach to “artificial life” style digital evolution of emergent phenomena, called “algorithmic chemistry.”   The basic concept was: Create small codelets, so that when codelet A acts on codelet B, it produces a new codelet C.   Then put a bunch of these codelets in a “primordial algorithmic soup” and let them act on each other, and see what interesting structures and dynamics emerge.

The paper reports some interesting emergent phenomena, but then the research programme was dropped off at an early stage.   Very broadly speaking, the story seems to have been similar to what happened with a lot of Alife-related work of that era: Some cool-looking self-organizational phenomena occurred, but not the emergence of highly complex structures and dynamics like the researchers were looking for.

These sorts of results spawned the natural question “why?”   Did the simulations involved not have a large enough scale?   (After all, the real primordial soup was BIG and based on parallel processing and apparently brewed for quite a long time before producing anything dramatic.)   Or were the underlying mechanisms simply not richly generative enough, in some way?   Or both?

What I am going to propose here is not so much a solution to this old “why” question, but rather a novel potential route around the problem that spawned the question.   My proposal – which I call “Cogistry” — is to enhance good old Fontana-style algorithmic chemistry by augmenting its “self-modifying program soup” with AI algorithms such as hypergraph pattern mining and probabilistic reasoning.   I believe that, if this is done right, it can lead to “algorithm soups” with robust, hierarchical, complex emergent structures – and also to something related but new and different: emergent, self-organizing program networks that carry out functions an AI agent desires for achievement of its goals.

That is: my aim with Cogistry is to use probabilistic inference and pattern mining to enhance algorithmic chemistry, so as to create “digital primordial soups” that evolve into interesting digital life-forms, but ALSO so as to create “life-like program networks” that transform inputs into outputs in a way that carries out useful functions as requested by an AI agent’s goal system.   The pure “digital primordial soup” case would occur when the inference and pattern mining are operating with the objective of spawning interesting structures and dynamics; whereas the “useful program network” case would occur when the inference and pattern mining are operating with an additional, specific, externally-supplied objective as well.

There is a rough analogy here with the relation between genetic algorithms and estimation of distribution algorithms (EDAs).   EDAs aim to augment GA mutation and crossover with explicit pattern mining and probabilistic reasoning.  But there are significant differences between EDAs and the present proposal as well.   There is a lot more flexibility in an algorithmic chemistry network than in an evolving populations of bit strings or typical GP program trees; and hence, I suspect, a lot more possibility for the “evolution/self-organization of evolvability” and the “evolution/self-organization of inferential analyzability” to occur.   Of course, though, this added flexibility also provides a lot more potential for messes to be made (including complex, original sorts of messes).

From an Alife point of view, the “chemistry” in the “algorithmic chemistry” metaphor is intended to be taken reasonably seriously.  A core intuition here is that to get rich emergent structures and dynamics from one’s “digital biology” it’s probably necessary to go a level deeper to some sort of “digital chemistry” with a rich combinatorial potential and a propensity to give rise to diverse stable structures, including some with complex hierarchical forms.    One might wonder whether this is even deep enough, whether one needs actually to dig down to a “digital physics” from which the digital chemistry emerges; my intuition is that this is not the case and focusing on the level of algorithmic chemistry (if it’s gotten right) is deep enough.

Actually, the “digital physics,” in the analogy pursued here, would be the code underlying the algorithms in the algorithm-soup: the programming-language interpreter and the underlying C and assembly code, etc.   So part of my suggestion here will be a suggestion regarding what kind of digital physics is likely to make algorithmic chemistry work best: e.g. functional programming and reversible computing.   But, according to my intuition, the core ideas of this “digital physics” have already been created by others for other purposes, and can be exploited for algorithmic-chemistry purposes without needing dramatic innovations on that level.

An Algorithmic Chemistry Framework

First I will define a framework for algorithmic chemistry in a reasonably general way.   I will then fill in more details, bit by bit.

The basic unit involved I will call a “codelet” – defined simply as a piece of code that maps one or more input codelets into one or more output codelets.   What language to use for specifying codelets is a subtle matter that I will address below, but that we don’t need to define in order to articulate a general algorithmic chemistry framework.

Fontana’s original work involved a chemical soup with no spatial structure, but other work with artificial life systems suggests that a spatial structure may be valuable.  So we propose a multi-compartment system, in which each compartment has its own “algorithmic chemical soup.”    A codelet, relative to a specific compartment, can be said to have a certain “count” indicating how many copies of that codelet exist in that compartment.

Inside each compartment, multiple dynamics happen concurrently:

  • Migration: codelets migrate from one compartment to neighboring compartments.    This can be done initially via random diffusion.
  • Importance spreading: codelets have short and long term importance values, which spread e.g. via ECAN dynamics
  • Forgetting: codelets with low long-term importance are “forgotten” from a compartment (and may or may not be saved to some persistent store, depending on system configuration)
  • Reaction: codelets in the compartment act on other codelets in the compartment, producing new codelets.   Codelets may be chosen for reaction with probability based on their short term importance values.
  • Generation: new codelets are introduced into the compartment, either representing inputs to the system from some external source, or generated randomly from some distribution, or drawn from some set of codelets believed to be generally useful

I will use the word “codenet” to refer to a collection of codelets that interact with each other in a coherent way.   This is intentionally a vague, intuitive definition – because there are many kinds of coherent networks of codelets, and it’s not obvious which ones are going to be the most useful to look at, in which contexts.   In some cases a chain of the form “In the presence of background codelet-set B, A1 reacts with B to make A2, which reacts with B to make A3, etc. …” may be very influential.   In other cases cycles of the form “A and B react to make C; then A and C create to make more B; and B and C react to make more A” may be critical.   In other cases it may be more complex sorts of networks.   Exactly how to chop up a soup of codelets, growing and interacting over time, into distinct or overlapping codenets is not entirely clear at present and may never be.   However, it’s clear that for understanding what is going on in an algorithmic-chemistry situation, it’s the codenets and not just the codelets that need to be looked at.   If codelets are like chemicals, then codenets are like chemical compounds and/or biological systems.

Implementation Notes

In terms of current computing architectures, it would be natural to run different compartments on different machines, and to run the four processes in different threads, perhaps with multiple threads handling reaction, which will generally be the most intensive process.

If implemented in an OpenCog framework, then potentially, separate compartments could be separate Atomspaces, and the dynamic processes could be separate MindAgents running in different threads, roughly similar to the agents now comprising the ECAN module.   Also, in OpenCog, codelets could be sub-hypergraphs in Atomspace, perhaps each codelet corresponding to a DefineLink.

Reactions would naturally be implemented using the Forward Chainer (a part of the Rule Engine, which leverages the Pattern Matcher).   This differs a bit from PLN’s use of the Forward Chainer, because in PLN one is applying an inference rule (drawn from a small set thereof) to premises, whereas here one is applying a codelet (drawn from a large set of possible codelets) to other codelets.

Measuring Interestingness

One interesting question is how to measure the interestingness of a codelet, or codenet.

For codelets, we can likely just bump the issue up a level: A codelet is as interesting as the codenets it’s part of.

For codenets, we can presumably rely on information theory.   A compartment, or a codenet, as it exists at a particular point in time, can be modeled using a sparse vector with an entry for each codelet that has nonzero count in the compartment or codenet (where the entry for a codelet contains the relevant count).      A compartment or codenet as it exists during an interval of time can then be modeled as a series of sparse vectors.   One can then calculate the interaction information of this vector-series (or the “surprisingness” as defined in the context of OpenCog’s Pattern Miner).   This is a good first stab at measuring how much novelty there is in the dynamics of a codenet or compartment.

In a codenet containing some codelets representing Inputs and others representing Outputs, one can also calculate interaction information based only on the Input and Output codelets.  This is a measure of the surprisingness or informativeness of the codenet’s relevant external behaviors, rather than its internal dynamics.

Pattern Mining and Inference for Algorithmic Chemistry

Given the above approach to assessing interestingness, one can use a modification of OpenCog’s Pattern Miner to search for codenets that have surprising dynamics.   One can also, in this way, search for patterns among codenets, so that specific codenets fulfilling the patterns have surprising dynamics.   Such patterns may be expressed in the Atomspace, in terms of “abstract codelets” — codelets that have some of their internal Atoms represented as VariableNodes instead.

An “abstract codenet” may be defined as a set of (possibly-abstract codelet, count-interval, time-interval) triples, where the time-interval is defined as a pair (start, end), where start and end are defined as offsets from the initiation of the codenet.   The interpretation of such a triple is that (C, (m,n) (s,e)) means that some codelet instantiating abstract codelet C exists with count between m and n, during the time interval spanning from s to e.

Note that in order to form useful abstractions from codenets involving different codelets, it will be useful to be able to represent codelets in some sort of normal form, so that comparison of different codelets is tractable and meaningful.  This suggests that having the codelet language support some sort of Elegant Normal Form, similar to the Reduct library used in OpenCog’s MOSES subsystem, will be valuable.

Using the Pattern Miner to search for abstract codenets with high degrees of informational surprisingness, should be a powerful way to drive algorithmic chemistry in interesting directions.   Once one has found abstract codenets that appear to systematically yield high surprisingness, one can then use these to drive probabilistic generation of concrete codenets, and let them evolve in the algorithmic soup, and see what they lead to.

Furthermore, once one has abstract codenets with apparent value, one can apply probabilistic inference to generalize from these codenets, using deductive, inductive and abductive reasoning, e.g. using OpenCog’s Probabilistic Logic Networks.   This can be used to drive additional probabilistic generation of concrete codenets to be tried out.

“Mutation” and “crossover” of codenets or codelets can be experimented with on the inferential level as well – i.e. one can ask one’s inference engine to estimate the likely interestingness of a mutation or crossover of observed codenets or codelets, and then try out the mutation or crossover products that have passed this “fitness estimation” test.

This kind of pattern mining and inference certainly will be far from trivial to get right.   However, conceptually, it seems a route with a reasonably high probability of surmounting the fundamental difficulties faced by earlier work in artificial life and algorithmic chemistry.   It is something conceptually different than “mere self-organization” or “mere logical reasoning” – it is Alife/Achem-style self-organization and self-modification, but explicitly guided by abstract pattern recognition and reasoning.   One is doing symbolic AI to accelerate and accentuate the creativity of subsymbolic AI.

The above pertains to the case where one is purely trying to create algorithmic soups with interesting internal dynamics and structures.   However, it applies also in cases where one is trying to use algorithmic chemistry to learn effective input-output functions according to some fitness criteria.   In that case, after doing pattern mining of surprising abstract codenets, one can ask a different question: Which codenets, and which combinations thereof, appear to differentially lead to high-fitness transformation of inputs into outputs?   One can then generate new codenets from the distribution obtained via answering this question.   This is an approach to solving the “assignment of credit” problem from a “God’s eye” point of view – by mining patterns from the network over time … a fundamentally different approach to assignment of credit than has been taken in subsymbolic AI systems in the past.

Desirable Properties of a Cogistry Codelet Language

Designing the right language for the above general “Cogistry” approach is a subtle task, and I won’t try to do so fully here.   I’ll just sketch some ideas and possible requirements.

Fontana’s original algorithmic chemistry work uses a variety of LISP, which seems a sound and uncontroversial choice (and the same choice we made in OpenCog’s MOSES GA-EDA tool, for example).   However, a few variations and additions to this basic LISP-ish framework seem potentially valuable:

  • Addition of unordered sets as primitives, alongside ordered lists; and then associated set operations
  • Addition of float-weighted lists and sets as primitives; and of basic vector operations acting on such lists, such as the dot product, and the multiplication of a vector by a scalar.

Float-weighted lists are very handy for dealing with perceptual data, for example.   They also provide an element of continuity, which may help with robustness.   Codelets relying on float vectors of weights can be modified slightly via modifying the weights, leading to codelets with slightly different behaviors – and this continuity may make learning of new codelets via sampling from distributions implied by abstract codenets easier.

Further, it seems to me we may want to make all operations reversible.  If the atomic operations on bits, ints and floats are reversible, then corresponding operations on lists and sets and weighted vectors can also easily be made reversible.  (For instance, removing the final element of a list can be made into a reversible operation by, instead, using an operation that splits a list into two parts: the list with the final element removed, and the final element itself.)   The intuition here is that reversibility introduces a kind of “conservation of information” into the system, which should prevent the advent of various sorts of pathological runaway dynamics like Fontana observed in his early simulations.   If codelets can produce “more” than they take in, then evolution will naturally lead to codelets that try to exploit this potential and produce more and more and more than they take in.   But if codelets have to be “conservative” and essentially act only by rearranging their inputs, then they have to be cleverer to survive and flourish, and are more strongly pushed to create complexly interlocking self-organizing structures.

I’m well aware that mining patterns among functions of float variables is difficult, and it would be easier to restrict attention to discrete variables – but ultimately I think this would be a mistake.   Perceptual data seems to be very naturally represented in terms of float vectors, for example.   Perhaps an innovative approach will be needed here, e.g. instead of floats one could use confidence intervals (x% chance of lying in the interval (L,U) ).   Reversible division on confidence intervals would require a bit of fiddling to work out, but seems unlikely to be fundamentally difficult.


The idea of Cogistry seemed very simple when I initially thought of it; but when I sat down to write this post summarizing it, it started to seem a lot more complicated.  There are a lot of moving parts!   But, hey, nobody said building a thinking machine and creating digital life in one fell swoop was going to be easy….   (Well actually OK, some people did say that… er, actually, I did say that, but I took it back a decade and a half ago!! …)

What I like about the idea of Cogistry, though, is that – if it works (and I’m sure it will, after a suitable amount of research and fiddling!) — it provides a way to combine the fabulous generative creativity of biological systems, with the efficiency and precision of digital-computer-based pattern mining and probabilistic reasoning.   Such a combination has the potential to transcend the “symbolic versus subsymbolic” and “biological versus computational” dichotomies that have plagued the AI field since nearly its inception (and that indeed reflect deeper complex dichotomies and confusions in our contemporary culture with its mixture of information-age, machine-age, and biological/emotional/cultural-humanity aspects).   Some of the details are gonna be freakin’ complicated to work out but, though I realize it sounds a bit vain or whatever, I have to say I feel there is some profound stuff lurking here…

Notes Toward a Possible Development Plan

At first blush, it seems to me that most of the hard work here is either

  • A) testing and experimenting; or
  • B) re-using OpenCog AI tools that we need anyway for other reasons

From this perspective, an approach to making Cogistry real would be to start by

  • designing the programming language (with room for experimentation/variation) for codelets
  • implementing the basic framework in OpenCog
  • doing some basic experimentation with this as an Alife/Achem framework, without the added AI bells and whistles

Now, I would not expect this initial work to yield great results… since basically it’s a matter of reimplementing good old Alife/Achem stuff in a context where inference, pattern mining, ECAN etc. can be layered on.  Without the layering on of these AI tools, one would expect to find familiar Alife-y issues: some interesting structures emerging, but hitting a complexity ceiling … and then being uncertain whether increased scale or a change to the codelet language might be the key to getting more interesting things to emerge.

But beyond this basic framework, the other things needed for Cogistry are all things needed for other OpenCog AGI work anyway:

  • more general use of pattern mining than has been done so far
  • PLN on output of pattern mining
  • ECAN working together w/ pattern mining and PLN
  • probabilistic programming for guiding the forward chainer

With the basic codelet-system framework in place, using these things for Cogistry alongside their other uses would be “straightforward in principle”

— Thanks are due to Cassio Pennachin and Zar Goertzel for comments on an earlier version of the text contained in this post.

Posted in Uncategorized | 9 Comments

Smart Contract Blockchains

Blockchains and smart contracts are all the rage, these days. What does this have to do with OpenCog?  Let me explain.


The idea of a block-chain comes from the idea of block ciphers, where you want to securely sign (or encrypt) some message, by chaining together blocks of data, in such a way that each prior encrypted block provides “salt” or a “seed” for the next block. Both bitcoin and git use block-chaining to provide cryptographic signatures authenticating the data that they store.  Now, git stores big blobs of ASCII text (aka “source code”), while bitcoin stores a very simple (and not at all general) general ledger.  Instead of storing text-blobs, like git, or storing an oversimplified financial ledger, like bitcoin, what if, instead, we could store general structured data?  Better yet: what if it was tuned for knowledge representation and reasoning? Better still: what if you could store algorithms in it, that could be executed? But all of these things together, and you’ve got exactly what you need for smart contracts: a “secure”, cryptographically-authenticated general data store with an auditable transaction history.  Think of it as internet-plus: a way of doing distributed agreements, world-wide.  It has been the cypher-punk day-dream for decades, and now maybe within reach. The rest of this essay unpacks these ideas a bit more.

Git vs. Bitcoin

When I say “git, the block-chain”, I’m joking or misunderstanding, I mean it.  Bitcoin takes the core idea of git, and adds a new component: incentives to provide an “Acked-by” or a “Signed-off-by” line, which git does not provide: with git, people attach Ack and Sign-off lines only to increase their personal status, rather than to accumulate wealth.  What is more, git does NOT handle acked-by/signed-off-by in a cryptographic fashion: it is purely manual; Torvalds or Andrew Morton or the other maintainers accumulate these, and they get added manually to the block chain, by cut-n-paste from email into the git commit message.

Some of the key differences between git and bitcoin are:

  • Bitcoin handles acked-by messages automatically, not manually, and they accumulate as distinct crypto signatures on the block-chain,  — by contrast, the git process is to cut-n-paste the acked-by sigs from the email and into the commit, and only then crypto-sign.    A modern  block-chain API should provide this automated acked-by handling that git does not.
  • Bitcoin provides (financial) incentives for people to generate acked-by messages: it does so through mining.  Unfortunately, mining is incredibly stupid and wasteful:  mining is designed to use immense amounts of cpu time before a new bitcoin is found.  This stupidity is to balance a human weakness, by appealing to human greed: the ability to get “free money” in exchange for the crypto-signed acked-by’s.  A modern block-chain API does NOT need to support mining, except maybe as an add-on feature so that it can say “hey, me too”.  Keeping up with the Jones’s.

For the things that I am interested in, I really don’t care about the mining aspect of blockchains. It’s just stupid.  Git is a superior block-chain to bitcoin.  It’s got more features, its got a better API, it offers consistent histories — that is, merging! Which bitcoin does not.  Understandably — bitcoin wants to prevent double-spending. But there are other ways to avoid double-spending, than to force a single master. Git shows the way.

Now, after building up git, it also has a lot of weaknesses: it does not provide any sort of built-in search or query.  You can say “git log” and view the commit messages, but you cannot search the contents: there is no such feature.

Structured Data

Git is designed for block-chaining unstructured ASCII (utf8) blobs of character strings — source-code, basically — it started life as a source-code control system.  Let’s compare that to structured data. So, in the 1960’s, the core concepts of relations and relational queries got worked out: the meaning of “is-a”, “has-a”, “part-of”, “is-owned-by”, etc. The result of this research was the concept of a relational database, and a structured query language (SQL) to query that structured data.  Businesses loved SQL, and Oracle, Sybase, IBM DB2 boomed in the 1970’s and 1980’s, and that is because the concept of relational data fit very well with the way that businesses organize data.

Lets compare SQL to bitcoin:  In bitcoin, there is only ONE relational table, and it is hard-coded. It can store only one thing: a quantity of bitcoin.  There is only one thing you can do to that table: add or remove bitcoin. That’s it.

In SQL, the user can design any kind of table at all, to hold any kind of data. Complete freedom.  So, if you wanted to implement block-chained smart contracts, that is what you would do: allow the user to create whatever structured data they might want.  For example: every month, the baker wants to buy X bags of flour from the miller for Y dollars: this is not just a contract, but a recurring contract: every month, it is the same.  To handle it, an SQL architect designs an SQL table to store dollars, bags of flour, multiple date-stamps: datestamp of when the order was made, date-stamp  of when the order was given to the shipping firm (who then crypto-signs the block-chain of this transaction), the datestamp of when the baker received the flour, the datestamp of when the baker paid the miller.  Each of these live on the block-chain, each get crypto-signed when the transaction occurs.

The SQL architect was able to design the data table in such a way that it is NATURAL for the purchase-ship-sell, inventory, accounts-payable, accounts-receivable way that this kind of business is conducted.

There are far more complicated transactions, in the petroleum industry, where revenue goes to pipeline owners, well owners, distillers, etc. in a very complicated process. Another example is the music-industry royalties.  Both of these industries use a rather complex financial ledger system that resemble financial derivatives, except that there is no futures contract structure to it: the pipeline owner cannot easily arbitrage the petroleum distiller. Anyway, this is what accounting programs and general ledgers excel at: they match up with the business process, and  the reason they can match up is because the SQL architect can design the database tables so that they fit well with the business process.

If you want to build a blockchain-based smart contract, you need to add structured data to the block-chain.  So this is an example of where git falls flat: its an excellent block-chain, but it can only store unstructured ASCII blobs.

Comparing Git to SQL: Git is also missing the ability to perform queries: but of course: the git data is unstructured, so queries are hard/impossible, by nature. A smart-contract block-chain MUST provide a query language!  Without that, it is useless. Let me say it again: SQL is KEY to business contracts.  If you build a blockchain without SQL-like features in it, it will TOTALLY SUCK. The world does not need another bitcoin!

I hope you have followed me so far.

The AtomSpace

OK, now, we are finally almost at where OpenCog is.  So: the idea of relational data and relational databases was fleshed out in the 1960’s and the 1970’s, and it appears to be enough for accounting.   However, it is not enough for other applications, in two different ways.

First, for “big data”, it is much more convenient to substitute SQL and ACID with NoSQL and BASE. The Google MapReduce system is a prime example of this.  It provides a highly distributed, highly-parallelizable query mechanism for structured data.   Conclusion: if you build a block-chain for structured data, but use only SQL-type PRIMARY-KEY’s for your tables, it will fail to scale to big-data levels.  Your block-chain needs to support both SQL and NoSQL.  The good news is that this is a “solved problem”: it is known that these are category-theoretic duals, there is a famous Microsoft paper on this: “ACM Queue March 18, 2011 Volume 9, issue 3 “A co-Relational Model of Data for Large Shared Data Banks”, Erik Meijer and Gavin Bierman, Microsoft. Contrary to popular belief, SQL and noSQL are really just two sides of the same coin.

Next problem: for the task of “knowledge representation” (ontology, triple-stores, OWL, SPARQL,) and “logical reasoning”, the flat tables and structures offered by SQL/noSQL are insufficient — it turns out that graphical databases are much better suited for this task. Thus, we have the concept of a graph_database, some well-known examples include Neo4j, tinkerpop, etc.

The OpenCog AtomSpace fits into this last category.  Here, the traditional 1960’s-era “is-a” relation corresponds to the OpenCog InheritanceLink.  Named relations (such as “Billy Bob is a part-time employee” in and SQL table) are expressed using EvaluationLinks and PredicateNodes:

    (PredicateNode "is-employee")
        (ConceptNode "BillyBob")
        (ConceptNode "employee")))

Its a bit verbose, but it is another way of expressing the traditional SQL relations.  It is somewhat No-SQL-like, because you do not have to declare an “is-employee” table in advance, the way you do in SQL — there  is no “hoisting” — instead, you can create new predicates dynamically, on the fly, at any time.

OpenCog has a centralized database, called the AtomSpace. Notice how the above is a tree, and so the  AtomSpace becomes a “forest of trees”. In the atomspace, each link or node is unique, and so each tree shares nodes and links: this is called a “Levi graph” and is a general bipartite way of representing hypergraphs.  So, the atomspace is not just a graph database, its a hypergraph database.

Edits to this database are very highly regulated and centralized: so there is a natural location where a blockchain signature could be computed: every time an atom is added or removed, that is a good place to hash the atomspace contents, and apply a signature.

The atomspace does NOT have any sort of history-of-transactions (we have not needed one, yet).  We are (actually, Nil is) working on something similar, though, called the “backwards-inference tree”, which is used to store a chain of logical deductions or inferences that get made.   Its kind-of-like a transaction history, but instead of storing any kind of transaction, it only stores those transactions that can be chained together to perform a forward-chained logical deduction.  Because each of these deductions lead to yet-another deduction, this is also a natural location to perform crypto block-chaining.  That is, if some early inference is wrong or corrupted, all later inferences become invalid – – that is the chaining.  So we chain, but we have not needed crypto signatures on that chain.

The atomspace also has a query language, called the “pattern matcher“.  It is designed to search only the current contents of the database.  I suppose it could be extended to search the transaction history.  The backward-inference-tree-chains were designed by Nil to be explicitly compatible with the pattern matcher.

The AtomSpace is a typed graph store, and some of the types are taken from predicate logic: there is a boolean AndLink, boolean OrLink, a boolean NotLink; but also an intuitionist-logic ChoiceLink, AbsentLink, PresentLink, and to round it out, a Kripke-frame ContextLink (similar to a CYC “microtheory” but much, much better). The reason I am mentioning these logic types is because they are the natural constructor types for smart contracts: in a legal contract, you want to say “this must be fulfilled and this or this but not this”, and so the logical connectives provide what you need for specifying contractual obligations.

Next, the AtomSpace has LambdaLinks, which implement the lambda abstractor from lambda calculus.  This enables generic computation: you need this for smart_contracts. The AtomSpace is NOT very strong in this area, though: it provides a rather basic computational ability with the LambdaLink, but it is very primitive, and does not go much farther.  We do some, but not a lot of computation in the AtomSpace.  It was not meant to be the kind of programming language that humans would want to code in.

The atomspace does NOT have any lambda flow in it, e.g. Marius Buliga’s ChemLambda.  I am still wrestling with that. The atomspace does have a distinct beta-reduction type, called PutLink, dual to the LambdaLink abstractor.  However, for theorem-proving, I believe that a few more abstractors are needed: Buliga has four: lambda and beta, and two more.  I am also trying to figure out Jean-Yves Girard’s Ludics.  Not there, yet.

Security, Scalability

Perhaps I failed to mention: the current AtomSpace design has no security features in it, whatsoever. Absolutely zero. Even the most trivial hostile action will wipe out everything.  There is a reason for this: development is focused on reasoning and thinking. Also, the current atomspace is not scalable.  It’s also rather low-performance. Its unsuitable for big-data. None of these checkboxes that many people look for are satisfied by the atomspace. That’s because these issues are, for this project, quite low priority. We are focused on reasoning and understanding, and just about nothing else.

So, taken at face value,  it is absurd to contemplate a blockchain for the atomspace; without even basic security, or decentralized, distributed storage, byzantine fault tolerance, and high performance, its a non-starter for serious consideration.  Can these checkboxes be added to the atomspace, someday? Maybe. Soon? Not at all likely.  These are nice-to-haves, but opencog’s primary focus must remain reasoning and thinking, not scalable, distributed, secure storage.


So that’s it, then: you can think of the OpenCog atomspace as a modern-day graphical, relational database that includes the datalog fragment of prolog, and lots of other parts as well.  It has an assortment of weaknesses and failures, which I know of, but won’t get into here. It is probably a decent rough sketch for the data storage system that you’d want for a block-chained smart contract.  To make it successful, you would need to a whole lotta things:

  • First, you’d need to actually get a real-life example of a smart-contract that people would want to have.
  • Next, you’d have to build a smart-phone app for it.
  • Next, it would have to appeal to some core class of users: I dunno — package tracking for UPS, or the collection of executive signatures by some legal dept, or maybe some accounts-receivable system that some billing dept. would want to use. There has got to be a hook: people have to want to use it.  It needs some magic ingredient.

The problem here is that, as a business, companies like IBM and PwC will trounce you at the high-end, cause they already have the business customers, and the IBM STSM’s are smart enough to figure out how block-chains work, and so will get some architects to create that kind of system for them.  At the low-end, there must be thousands of twenty-something programmers writing apps for cell-phones, daydreaming of being the next big unicorn, and they are all exploring payment systems and smart-cards and whatever, at a furious pace.  So if you really want a successful block-chain, smart-contract business, here, hold on to your butt.

I think that the only hope is to go open source, work with the Apache foundation, have them do the marketing for the AtomSpace or something like it, and set up API’s that people want to use.   That’s a lot of work.  But that is the way to go.

Posted in Design, Theory, Uncategorized | 2 Comments

Many Worlds: Reasoning about Reasoning

When one reasons about the world, what is one actually doing? This post is about that.

OpenCog has a reasoning system, called PLN, short for “Probabilistic Logic Networks”.  Its actually two things: first and foremost, its a set of “rules of inference”, which can be applied to “real world knowledge”, to deduce new “facts” about the world.  There are about half a dozen of these rules, and one of them resembles the classical “Modus Ponens“, except that it assigns a probability to the outcome, based on the probabilities of the inputs.  For the rest of this post, the details of PLN mostly don’t matter: if you wish, you can think of classical propositional logic, or of some kind of fuzzy logic, if you wish, or even competing systems such as NARS.  Anyway, PLN applies these rules of inference to the Atoms contained in the AtomSpace, to generate new Atoms. This is a fancy way of saying that the AtomSpace is the knowledge repository in OpenCog, an that the atoms are the “facts”. Its not much more than that: its just a big jumble of facts.

I want to talk about reasoning using PLN.  Now, this is NOT the way that the current opencog code base implements PLN reasoning; however, its a conceptual description of what it could (or should, or might) do.

Now, I mentioned that PLN consists of maybe a half-dozen or a dozen rules of inference.  They have fancy names like “modus ponens” but we could call them just “rule MP” … or just “rule A”, “rule B”, and so on.

Suppose I start with some atomspace contents, and apply the PLN rule A. As a result of this application, we have a “possible world 1”.  If, instead, we started with the same original atomspace contents as before, but applied rule B, then we would get “possible world 2”.  It might also be the case that PLN rule A can be applied to some different atoms from the atomspace, in which case, we get “possible world 3”.

Each possible world consists of the triple (some subset of the atomspace, some PLN inference rule, the result of applying the PLN rule to the input). Please note that some of these possible worlds are invalid or empty: it might not be possible to apply the choosen PLN rule to the chosen subset of the atomspace.  I guess we should call these “impossible worlds”.  You can say that their probability is exactly zero.

Observe that the triple above is an arrow:  the tail of the arrow is “some subset of the atomspace”, the head of the arrow is “the result of applying PLN rule X”, and the shaft of the arrow is given a name: its “rule X”. (In fancy-pants, peacock language, the arrows are morphisms, and the slinging together, here, are Kripke frames. But lets avoid the fancy language since its confuses things a lot. Just know that it’s there.)

Anyway — considering this process, this clearly results in a very shallow tree, with the original atomspace as the root, and each branch of the tree corresponding to possible world.  Note that each possible world is a new and different atomspace: The rules of the game here are that we are NOT allowed to dump the results of the PLN inference back into the original atomspace.  Instead, we MUST fork the atomspace.  Thus, if we have N possible worlds, then we have N distinct atomspaces (not counting the original, starting atomspace).  This is very different from what the PLN code base does today: it currently dumps its results back into the original atomspace. But, for this conceptual model, we don’t want to do that.

Now, for each possible world, we can apply the above procedure again. Naively, this is a combinatoric explosion. For the most part, each different possible world will be different than the others. They will share a lot of atoms in common, but some will be different. Note, also, that *some* of these worlds will NOT be different, but will converge, or be “confluent“, arriving at the same atomspace contents along different routes.  So, although, naively, we have a highly branching tree, it should be clear that sometimes, some of the branches come back together again.

I already pointed out that some of the worlds are “impossible” i.e. have a probability of zero. These can be discarded.  But wait, there’s more.  Suppose that one of the possible worlds contains the statement “John Kennedy is alive” (with a very very high confidence) , while another one contains the statement “John Kennedy is dead” (with a very very high confidence).  What I wish to claim is that, no matter what future PLN inferences might be made, these two worlds will never become confluent.

There is also a different effect: during inferencing (i.e. the repeated application of PLN), one might find oneself in a situation where the atoms being added to the atomspace, at each inference step, have lower and lower probability. At some point, this suggests that one should just plain quit — that particular branch is just not going anywhere. Its a dead end. A similar situation occurs when no further PLN rules can be applied. Dead end.

OK, that’s it.  The above provides a very generic description of how inferencing can be performed. It doesn’t have to be PLN — it could be anything — classical logic using sequent calculus, for example.  So far, everything I said is very easy-peasy, direct and straightforward. So now is where the fun starts.

First, (lets get it out of the way now) the above describes *exactly* how Link Grammar works.  For “atomspace” substitute “linkage” and for “PLN rule of inference” substitute “disjunct“.  That’s it. End of story. QED.

Oh, I forgot to introduce Link Grammar.  It is a system for parsing natural languages, such as English.  It does this by maintaining a dictionary of so-called “disjuncts”, which can be thought of “jigsaw puzzle pieces”.  The act of parsing requires finding and joining together the jigsaw pieces into a coherent whole.  The final result of the act of parsing is a linkage (a parse is a linkage – same thing).  These jigsaw puzzle pieces are nicely illustrated in the very first paper on Link Grammar.

Notice that each distinct linkage in link-grammar is a distinct possible-world. The result of parsing is to create a list of possible worlds (linkages, aka “parses”).  Now, link-grammar has a “cost system” that assigns different probabilities (different costs) to each possible world: this is “parse ranking”: some parses (linkages) are more likely than others. Note that each different parse is, in a sense, “not compatible” with every other parse.  Two different parses may share common elements, but other parts will differ.

Claim: the link-grammar is a closed monoidal category, where the words are the objects, and the disjuncts are the morphisms. I don’t have the time or space to articulate this claim, so you’ll have to take it on faith, or think it through, or compare it to other papers on categorial grammar or maybe pregroup grammar. There is nice example from Bob Coecke showing the jigsaw-puzzle pieces.  You can see a similar story develop in John Baez’s “Rosetta Stone” paper, although the jigsaw-pieces are less distinctly illustrated.

Theorem: the act of applying PLN, as described above, is a closed monoidal category. Proof:  A “PLN rule of inference” is, abstractly, exactly the same thing as a link-grammar disjunct. The contents of the atomspace is exactly the same thing as a (partially or fully) parsed sentence.  QED.

There is nothing more to this proof than that.  I mean, it can fleshed it out in much greater detail, but that’s the gist of it.

Observe two very important things:  (1) During the proof, I never once had to talk about modus ponens, or any of the other PLN inference rules.  (2) During the proof, I never had to invoke the specific mathematical formulas that compute the PLN “TruthValues” — that compute the strength and confidence.   Both of these aspects of PLN are completely and utterly irrelevant to the proof.  The only thing that mattered is that PLN takes, as input, some atoms, and applies some transformation, and generates atoms. That’s it.

The above theorem is *why* I keep talking about possible worlds and kripke-blah-blah and intuitionistic logic and linear logic. Its got nothing to do with the actual PLN rules! The only thing that matters is that there are rules, that get applied in some way.  The generic properties of linear logic and etc. are the generic properties of rule systems and Kripke frames. Examples of such rule systems include link-grammar, PLN, NARS, classical logic, and many more.  The details of the specific rule system do NOT alter the fundamental process of rule application aka “parsing” aka “reasoning” aka “natural deduction” aka “sequent calculus”.    In particular, it is a category error to confuse the details of PLN with the act of parsing: the logic that describes parsing is not PLN, and PLN dos not describe parsing: its an error to confuse the two.


What remains to be done:  I believe that what I describe above, the “many-worlds hypothesis” of reasoning, can be used to create a system that is far more efficient than the current PLN backward/forward chainer.  It’s not easy, though: the link-parser algorithm struggles with the combinatoric explosion, and has some deep, tricky techniques to beat it down.  ECAN was invented to deal with the explosion in PLN.  But there are other ways.

By the way: the act of merging the results of a PLN inference back into the original atomspace corresponds, in a very literal sense, to a “wave function collapse”. As long as you keep around multiple atomspaces, each containing partial results, you have “many worlds”, but every time you discard or merge some of these atomspaces back into one, its a “collapse”.  That includes some of the truth-value merge rules that currently plague the system. To truly understand these last three sentences, you will, unfortunately, have to do a lot of studying. But I hope this blog post provides a good signpost.

Posted in Design, Development, Theory | 8 Comments

Putting Deep Perceptual Learning in OpenCog

This post presents some speculative ideas and plans, but I broadcast them here because I think they are of particular strategic importance for the OpenCog project….
The topic is: how OpenCog and “current-variety deep learning perception algorithms” can help each other.
Background: Modern Deep Learning Networks

“Deep learning” architectures have worked wonders on visual and auditory data in recent years, and have also shown limited interesting results on other sorts of data such as natural language.   The impressive applications have all involved training deep learning nets using a supervised learning methodology, on large training corpora; and the particulars of the network tend to be specifically customized to the problem at hand.   There is also work on unsupervised learning, though so far purely unsupervised learning has not yielded practically impressive results.  There is not much new conceptually in the new deep learning work, and nothing big that’s new mathematically; it’s mostly the availability of massive computing power and training data that has led to the recent, exciting successes…
These deep learning methods are founded on broad conceptual principles, such as
  • intelligence consists largely of hierarchical pattern recognition — recognition of patterns within patterns within patterns.. —
  • a mind should use both bottom-up and top-down dynamics to recognize patterns in a given data-item based on its own properties and based on experience from looking at other items
  • in many cases, the dimensional structure of spacetime can be used to guide hierarchical pattern recognition (so that patterns higher-up in the hierarchy pertain to larger regions of spacetime)
However, the tools normally labeled “deep learning” these days constitute a very, very particular way of embodying these general principles, using certain sorts of “formal neural nets” and related structures.  There are many other ways to manifest the general principles of “hierarchical pattern recognition via top-down and bottom-up learning, guided by spatiotemporal structure.”
The strongest advocates of the current deep learning methods claim that the deep networks currently used for perception, can be taken as templates or at least close inspirations for creating deep networks to be used for everything else a human-level intelligence needs to do.  The use of human-labeled training examples obviously doesn’t constitute a general-intelligence-capable methodology, but if one substitutes a reinforcement signal for a human label, then one has an in-principle workable methodology.
Weaker advocates claim that networks such as these may serve as a large part of a general intelligence architecture, but may ultimately need to be augmented by other components with (at least somewhat) different structures and dynamics.
It is sometimes suggested that the “right” deep learning network might serve the role of the “one crucial learning algorithm” underlying human and human-like general intelligence.   However, the deep learning paradigm does not rely on this idea… it might also be that a human-level intelligence requires a significant number of differently-configured deep networks, connected together in an appropriate architecture.
Deep Learning + OpenCog

My own intuition is that, given the realities of current (or near future) computer hardware technology, deep learning networks are a great way to handle visual and auditory perception and some other sorts of data processing; but that for many other critical parts of human-like cognition, deep learning is best suited for a peripheral role (or no role at all).   Based on this idea, Ted Sanders, Jade O’Neill and I did some prototype experiments a few years ago, connecting a deep learning vision system (DeSTIN) with OpenCog via extracting patterns from DeSTIN states over time and importing relations among these patterns into the OpenCog Atomspace.   This prototype work served to illustrate a principle, but did not represent a scalable methodology (the example dataset used was very small, and the different components of the architecture were piped together using ad hoc specialized scripts).
I’ve now started thinking seriously about how to resume this direction of work, but “doing it for real” this time.   What I’d like to do is build a deep learning architecture inside OpenCog, initially oriented toward vision and audition, with a goal of making it relatively straightforward to interface between deep learning perception networks and OpenCog’s cognitive mechanisms.
What cognitive mechanisms am I thinking of?
  1. The OpenCog Pattern Miner, written by Shujing Ke (in close collaboration with me on the conceptual and math aspects), can be used to recognize (frequent or surprising) patterns among states of a deep learning network — if this network’s states are represented as Atoms.   Spatiotemporal patterns among these “generally common or surprising” patterns may then be recognized and stored in the Atomspace as well. Inference may be done, using PLN, on the links representing these spatiotemporal patterns.  Clusters of spatiotemporal patterns may be formed, and inference may be done regarding these clusters.
  2. Having recognized common patterns within a set of states of a deep network, one can then annotate new deep-network states with the “generally common patterns” that they contain.   One may then use the links known in the Atomspace regarding these patterns, to create new *features* associated with nodes in the deep-network.  These features may be used as inputs for the processing occurring within the deep network.
This would be a quite thorough and profound form of interaction between perceptual and cognitive algorithms.
This sort of interaction could be done without implementing deep learning networks in the Atomspace, but it will be much easier operationally if they are represented in the Atomspace.
A Specific Proposal
So I’ve put together a specific proposal for putting deep learning into OpenCog, for computer vision (at first) and audition.   In its initial version, this would let one build quite flexible deep learning networks in OpenCog, deferring the expensive number-crunching operations to the GPU via the Theano library developed by Yoshua Bengio’s group at U. Montreal.
As it may get tweaked and improved or augmented by others, I’ve put it at the OpenCog wiki site instead of packing it into this blog post… you can read it at
Posted in Uncategorized | 10 Comments