text
stringlengths
3.69k
846k
labels
int64
0
1
PROC. OF THE 6th EUR. CONF. ON PYTHON IN SCIENCE (EUROSCIPY 2013) 59 JyNI – Using native CPython-Extensions in Jython Stefan Richthofer∗† F arXiv:1404.6390v2 [cs.PL] 29 Apr 2014 CPython JyNI Fig. 1: Extensions Fig. 2: JyNI Abstract—Jython is a Java based Python implementation and the most seamless way to integrate Python and Java. However, it does not support native extensions written for CPython like NumPy or SciPy. Since most scientific Python code fundamentally depends on exactly such native extensions directly or indirectly, it usually cannot be run with Jython. JyNI (Jython Native Interface) aims to close this gap. It is a layer that enables Jython users to load native CPython extensions and access them from Jython the same way as they would do in CPython. In order to leverage the JyNI functionality, you just have to put it on the Java classpath when Jython is launched. It neither requires you to recompile the extension code, nor to build a customized Jython fork. That means, it is binary compatible with existing extension builds. At the time of writing, JyNI does not fully implement the Python C-API and it is only capable of loading simple examples that only involve most basic builtin types. The concept is rather complete though and our goal is to provide the C-API needed to load NumPy as soon as possible. After that we will focus on SciPy and others. We expect that our work will also enable Java developers to use CPython extensions like NumPy in their Java code. the frequent occurrence of preprocessor macros in the public C-API allows for no naive approaches like directly delegating every C-API call to Jython. It turned out, that most built-in types need individual fixes, considerations and adjustments to allow seamless integration with Jython. There have been similar approaches for other Python implementations, namely [IRONCLAD] for IronPython and [CPYEXT] for PyPy. As far as we know, these suffer from equal difficulties as JyNI and also did not yet reach a satisfying compatibility level for current Python versions. Another interesting work is NumPy4J [NP4J], which provides Java interfaces for NumPy by embedding the CPython interpreter. It features automatic conversion to Java suitable types and thus allows easy integration with other Java frameworks. A more general approach is Jepp [JEPP], which also works via embedding the CPython interpreter. It also includes conversion methods between basic Python and Java types, but is not specifically NumPy-aware. However, none of these approaches aims for integration with Jython. In contrast to that, JyNI is entirely based on Jython. Though large parts are derived from CPython, the main Python runtime is provided by Jython and JyNI delegates most C-API calls to Jython directly or indirectly (i.e. some objects are mirrored natively, so calls to these can be processed entirely on native side, syncing the results with Jython afterwards; see implementation section for details). Index Terms—Jython, Java, Python, CPython, extensions, integration, JNI, native, NumPy, C-API, SciPy 1 I NTRODUCTION [JyNI] is a compatibility layer with the goal to enable [JYTHON] to use native CPython extensions like NumPy or SciPy. This way we aim to enable scientific Python code to run on Jython. Since Java is rather present in industry, while Python is more present in science, JyNI is an important step to lower the cost of using scientific code in industrial environments. Because of the complexity of the Python C-API, the task of developing JyNI revealed to be a true challenge. Especially * Corresponding author: [email protected] † Institute for Neural Computation, Ruhr-Universität Bochum c 2014 Stefan Richthofer. This is an open-access article disCopyright ○ tributed under the terms of the Creative Commons Attribution License, which permits unrestricted use, distribution, and reproduction in any medium, provided the original author and source are credited. http://creativecommons.org/licenses/by/3.0/ 2 U SAGE Thanks to Jython’s hooking capabilities, it is sufficient to place JyNI.jar on the classpath (and some native libraries on the library path) when Jython is launched. Then Jython should “magically” be able to load native extensions, as far as the needed Python C-API is already implemented by JyNI. No recompilation, no forking – it just works with original Jython and original extensions (up to version compatibility; see the versioning notes at the end of this section). 60 PROC. OF THE 6th EUR. CONF. ON PYTHON IN SCIENCE (EUROSCIPY 2013) Note that the naive way does not actually set the classpath for Jython: java -cp "[...]:JyNI.jar:[JyNI binaries folder]" -jar jython.jar The correct way is: The second part of the JyNI version (currently alpha.2.1) indicates the development status. As long as it contains “alpha” or “beta”, one can’t expect that the targeted API version is already met. Once out of beta, we will maintain this version part as a third index of the targeted API version (i.e. JyNI 2.7.x). java -cp "[...]:JyNI.jar:[JyNI binaries folder]: jython.jar" org.python.util.jython Alternatively, one can use Jython’s start script: jython -J-cp "[...]:JyNI.jar:[JyNI binaries folder]" Usually the JVM does not look for native library files on the classpath. To ease the configuration, we built into JyNI’s initializer code that it also searches for native libraries on the classpath. Alternatively you can place libJyNI.so and libJyNI-loader.so anywhere the JVM finds them, i.e. on the java library path (java.library.path) or the system’s library path (LD_LIBRARY_PATH). To get an impression of JyNI, proceed as described in the following subsection. 2.1 Instructions to run JyNIDemo.py Go to [JyNI], select the newest release in the download section and get the sources and binaries appropriate for your system (32 or 64 bit). • Extract JyNI-Demo/src/JyNIDemo.py from the sources. • To launch it with CPython, extract DemoExtension.so from the bin archive. • JyNIDemo.py adds the extension folder via sys.path.append([path]). You can modify that line so it finds your extracted DemoExtension.so or delete the line and put DemoExtension.so on the pythonpath. • If you launch JyNIDemo.py with Jython, it won’t work. Put JyNI.jar, libJyNI-Loader.so and libJyNI.so on Jython’s classpath. libJyNI-Loader.so and libJyNI.so can alternatively be placed somewhere on the Java library path. Jython should now be able to run JyNIDemo.py via • java -cp "[...]:JyNI.jar:[JyNI binaries folder]: jython.jar" org.python.util.jython JyNIDemo.py Be sure to use Jython 2.7 (beta) or newer. If you are not using the Jython stand-alone version, make sure that Jython’s Libfolder is on the Python path. 2.2 Versioning note JyNI’s version consists of two parts. The first part (currently 2.7) indicates the targeted API version. Your Jython should meet this version if you intend to use it with JyNI. For extensions, the API version means that a production release of JyNI would be able to load any native extension that a CPython distribution of the same version (and platform) can load. Of course, this is an idealistic goal – there will always remain some edgy, maybe exotic API-aspects JyNI won’t be able to support. 3 C APABILITIES JyNI is currently available for Linux only. Once it is sufficiently complete and stable, we will work out a cross platform version compilable on Windows, Mac OS X and others. The following built-in types are already supported: • Number types PyInt, PyLong, PyFloat, PyComplex • Sequence types PyTuple, PyList, PySlice, PyString, PyUnicode • Data structure types PyDict, PySet, PyFrozenSet • Operational types PyModule, PyClass, PyMethod, PyInstance, PyFunction, PyCode, PyCell • Singleton types PyBool, PyNone, PyEllipsis, PyNotImplemented • Native types PyCFunction, PyCapsule, PyCObject • Natively defined custom types • Exception types • PyType as static type or heap type The function families PyArg_ParseTuple and Py_BuildValue are also supported. 4 I MPLEMENTATION To create JyNI we took the source code of CPython 2.7 and stripped away all functionality that can be provided by Jython and is not needed for mirroring objects (see below). We kept the interface unchanged and implemented it to delegate calls to Jython via JNI and vice versa. The most difficult thing is to present JNI jobject s from Jython to extensions such that they look like PyObject* from Python (C-API). For this task, we use the three different approaches explained below, depending on the way a native type is implemented. In this section, we assume that the reader is familiar with the Python [C-API] and has some knowledge about the C programming language, especially about the meaning of pointers and memory allocation. 4.1 Python wraps Java The best integration with Jython is obtained, if PyObject* is only a stub that delegates all its calls to Jython (figure 3). This is only possible, if Jython features a suitable counterpart of the PyObject (i.e. some subclass of org.python.core.PyObject with similar name, methods and functionality). Further, there must not exist macros in the official C-API that directly access the PyObject’s memory. Consequently, one cannot use tp_dictoffset to obtain the object’s dictionary or offset from PyMemberDef to access the object’s members. JYNI – USING NATIVE CPYTHON-EXTENSIONS IN JYTHON PyObject* jobject Fig. 3: Python wraps Java 61 store its backend. We wrote a wrapper, that provides access to the memory of the C struct of PyListObject and implements the java.util.List interface on Java side. If a PyList is mirrored, we replace its backend by our wrapper. If it was initially created on the Jython side, we insert all its elements into the C counterpart on initialization. PyCell and PyByteArray are other examples that need mirror mode, but are mutable. However, we have rough ideas how to deal with them, but since they are not used by NumPy, we don’t put priority on implementing them. PyObject* 4.3 jobject Fig. 4: Objects are mirrored Since members are usually only accessed via generic getter or setter methods that also look for a PyGetSetDef with the right name, we usually re-implement the members as get-sets. Also the dictionary access is usually performed in methods we can safely rewrite to versions that get the dictionary from Jython. Examples for this method are PyDict, PySlice and PyModule. The cases where this approach fails are • if Jython features no corresponding type • if the Python C-API features macros to access the Object’s memory directly We deal with these cases in the following. 4.2 Mirroring objects If the Python C-API provides macros to access an object’s data, we cannot setup the object as a stub, because the stub would not provide the memory positions needed by the macros. To overcome this issue, we mirror the object if its C-API features such direct access macros (figure 4). Examples, where this approach is successfully applied are PyTuple, PyList, PyString, PyInt, PyLong, PyFloat and PyComplex. The difficulty here is to provide a suitable synchronization between the counterparts. If the CPython object is modified by C code, these changes must be reflected immediately on Jython side. The problem here is, that such changes are not reported; they must be detected. Performing the synchronization when the C call returns to Jython is only suitable, if no multiple threads exist. However, most of the affected objects are immutable anyway, so an initial data synchronization is sufficient. PyList is an example for an affected object that is mutable via a macro. For PyList, we perform an individual solution. The Jython class org.python.core.PyList uses a variable of type java.util.List (which is an interface) to Java wraps Python If Jython provides no counterpart of an object type, the two approaches described above are not feasible. Typically, this occurs, if an extension natively defines its own PyType objects, but there are also examples for this in the original Python C-API. If the types were previously known, we could simply implement Jython counterparts for them and apply one of the two approaches above. However, we decided to avoid implementing new Jython objects if possible and solve this case with a general approach. PyCPeer extends org.python.core.PyObject and redirects the basic methods to a native PyObject* (figure 5). The corresponding PyObject* pointer is tracked as a java long in PyCPeer. Currently PyCPeer supports attribute access by delegating __findattr_ex__, which is the backend method for all attribute accessing methods in Jython (i.e. __findattr__ and __getattr__ in all variants). Further, PyCPeer delegates the methods __str__, __repr__ and __call__. A more exhaustive support is planned. PyCPeerType is a special version of PyCPeer that is suited to wrap a natively defined PyType. Let’s go through an example. If you execute the Python code "x = foo.bar", Jython compiles it equivalently to the Java call "x = foo.__getattr__("bar");". If foo is a PyCPeer wrapping a native PyObject*, Java’s late binding would call __findattr_ex__("bar") implemented in PyCPeer. Via the native method JyNI.getAttrString(long peerHandle, String name) the call is delegated to JyNI_getAttrString in JyNI.c and then finally to PyObject_GetAttrString in object.c. To convert arguments and return values between Java jobject and CPython PyObject*, we use the conversion methods JyNI_JythonPyObject_FromPyObject and JyNI_PyObject_FromJythonPyObject (see next section). Our version of PyObject_GetAttrString falls back to the original CPython implementation, if it is called with a PyCPeer or a mirrored object. A flag in the corresponding JyObject (see next section) allows to detect these cases. An example from the C-API that needs the approach from this section is PyCFunction. 4.4 Object lookup Every mentioned approach involves tying a jobject to a PyObject*. To resolve this connection as efficiently as possible, we prepend an additional header before each PyObject 62 PROC. OF THE 6th EUR. CONF. ON PYTHON IN SCIENCE (EUROSCIPY 2013) PyObject* jobject Fig. 5: Java wraps Python ... jobject, ags, meta (PyGC_Head) PyObject ... info PyObject* Fig. 6: Memory layout in memory. If a PyGC_Head is present, we prepend our header even before that, as illustrated in figure 6. In the source, this additional header is called JyObject and defined as follows: typedef struct { jobject jy; unsigned short flags; JyAttribute* attr; } JyObject; jy is the corresponding jobject, flags indicates which of the above mentioned approaches is used, whether a PyGC_Head is present, initialization state and synchronization behavior. attr is a linked list containing void pointers for various purpose. However, it is intended for rare use, so a linked list is a sufficient data structure with minimal overhead. A JyObject can use it to save pointers to data that must be deallocated along with the JyObject. Such pointers typically arise when formats from Jython must be converted to a version that the original PyObject would have contained natively. To reserve the additional memory, allocation is adjusted wherever it occurs, e.g. when allocations inline as is the case for number types. The adjustment also occurs in PyObject_Malloc. Though this method might not only be used for PyObject allocation, we always prepend space for a JyObject. We regard this slight overhead in nonPyObject cases as preferable over potential segmentation fault if a PyObject is created via PyObject_NEW or PyObject_NEW_VAR. For these adjustments to apply, an extension must be compiled with the WITH_PYMALLOC flag activated. Otherwise several macros would direct to the raw C methods malloc, free, etc., where the neccessary extra memory would not be reserved. So an active WITH_PYMALLOC flag is crucial for JyNI to work. However, it should be not much effort to recompile affected extensions with an appropriate WITH_PYMALLOC flag value. Statically defined PyType objects are treated as a special case, as their memory is not dynamically allocated. We resolve them simply via a lookup table when converting from jobject to PyObject* and via a name lookup by Java reflection if converting the other way. PyType objects dynamically allocated on the heap are of course not subject of this special case and are treated like usual PyObject s (the Py_TPFLAGS_HEAPTYPE flag indicates this case). The macros AS_JY(o) and FROM_JY(o), defined in JyNI.h, perform the necessary pointer arithmetics to get the JyObject header from a PyObject* and vice versa. They are not intended for direct use, but are used internally by the high-level conversion functions described below, as these also consider special cases like singletons or PyType objects. The other lookup direction is done via a hash map on the Java side. JyNI stores the PyObject* pointers as Java Long objects and looks them up before doing native calls. It then directly passes the pointer to the native method. The high-level conversion functions jobject JyNI_JythonPyObject_FromPyObject (PyObject* op); PyObject* JyNI_PyObject_FromJythonPyObject (jobject jythonPyObject); take care of all this, do a lookup and automatically perform initialization if the lookup fails. Of course the jobject mentioned in these declarations must not be an arbitrary jobject, but one that extends org.python.core.PyObject. Singleton cases are also tested and processed appropriately. NULL converts to NULL. Though we currently see no use case for it, one can use the declarations in JyNI.h as JyNI C-API. With the conversion methods one could write hybrid extensions that do C, JNI and Python calls natively. 4.5 Global interpreter lock (GIL) The global interpreter lock is a construction in CPython that prevents multiple threads from running Python code in the same process. It is usually acquired when the execution of a Python script begins and released when it ends. However, a native extension and some parts of native CPython code can release and re-acquire it by inserting the Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macros. This way, an extension can deal with multiple threads and related things like input events (f.i. Tkinter needs this). In contrast to that, Jython does not have a GIL and allows multiple threads at any time, using Java’s threading architecture. Since native extensions were usually developed for CPython, some of them might rely on the existence of a GIL and might produce strange behaviour if it was missing. So JyNI features a GIL to provide most familiar behaviour to loaded extensions. To keep the Java parts of Jython GIL-free and have no regression to existing multithreading features, the JyNI GIL is only acquired when a thread enters native code and released when it enters Java code again – either by returning from the native call or by performing a Java call to Jython code. Strictly speaking, it is not really global (thus calling it “GIL” is a bit misleading), since it only affects threads in native code. While there can always be multiple threads in Java, there can only be one thread in native code at the same time (unless the above mentioned macros are used). JYNI – USING NATIVE CPYTHON-EXTENSIONS IN JYTHON 63 6 Fig. 7: Tkinter demonstration 5 A REAL - WORLD EXAMPLE : T KINTER To present a non-trivial example, we refere to Tkinter, one of the most popular GUI frameworks for Python. There has already been an approach to make Tkinter available in Jython, namely jTkinter – see [JTK]. However, the last update to the project was in 2000, so it is rather outdated by now and must be considered inactive. A NOTHER EXAMPLE : T HE D A T E T I M E MODULE As a second example, we refere to the datetime module. Jython features a Java-based version of that module, so this does not yet pay off in new functionality. However, supporting the original native datetime module is a step toward NumPy, because it features a public C-API that is needed by NumPy. The following code demonstrates how JyNI can load the original datetime module. Note that we load it from the place where it is usually installed on Linux. To overwrite the Jython version, we put the new path to the beginning of the list in sys.path: import sys sys.path.insert(0, ’/usr/lib/python2.7/lib-dynload’) import datetime print datetime.__doc__ print "-" * 22 print print datetime.__name__ now = datetime.datetime(2013, 11, 3, 20, 30, 45) print now print repr(now) print type(now) Since release alpha.2.1, JyNI has been tested successfully on basic Tkinter code. We load Tkinter from the place where it is usually installed on Linux: To verify that the original module is loaded, we print out the __doc__ string. It must read "Fast implementation of the datetime type.". If JyNI works as excpected, the output is: import sys #Include native Tkinter: sys.path.append(’/usr/lib/python2.7/lib-dynload’) sys.path.append(’/usr/lib/python2.7/lib-tk’) Fast implementation of the datetime type. ---------------------- from Tkinter import * root = Tk() txt = StringVar() txt.set("Hello World!") def print_text(): print txt.get() def print_time_stamp(): from java.lang import System print "System.currentTimeMillis: " +str(System.currentTimeMillis()) Label(root, text="Welcome to JyNI Tkinter-Demo!").pack() Entry(root, textvariable=txt).pack() Button(root, text="print text", command=print_text).pack() Button(root, text="print timestamp", command=print_time_stamp).pack() Button(root, text="Quit", command=root.destroy).pack() root.mainloop() Note that the demonstration also runs with CPython in principle. To make this possible, we perform from java.lang import System inside the method body of print_time_stamp rather than at the beginning of the file. Thus, only the button “print timestamp” would produce an error, since it performs Java calls. In a Jython/JyNI environment, the button prints the current output of java.lang.System.currentTimeMillis() to the console (see figure 7). datetime 2013-11-03 20:30:45 datetime.datetime(2013, 11, 3, 20, 30, 45) <type ’datetime.datetime’> 7 R OADMAP The main goal of JyNI is compatibility with NumPy and SciPy, since these extensions are of most scientific importance. Since NumPy has dependencies on several other extensions, we will have to ensure compatibility with these extensions first. Among these are ctypes and datetime (see previous section). In order to support ctypes, we will have to support the PyWeakRef object. 7.1 Garbage Collection Our first idea to provide garbage collection for native extensions, was to adopt the original CPython garbage collector source and use it in parallel with the Java garbage collector. The CPython garbage collector would be responsible to collect mirrored objects, native stubs and objects created by native extensions. The stubs would keep the corresponding objects alive by maintaining a global reference. However, this approach does not offer a clean way to trace reference cycles through Java/Jython code (even pure Java Jython objects can be part of reference cycles keeping native objects alive forever). To obtain a cleaner solution, we plan to setup an architecture that makes the native objects subject to Java’s garbage collector. The difficulty here is that Java’s mark and sweep algorithm only traces Java objects. When a Jython object is collected, we can use its finalizer to clean up the corresponding 64 PROC. OF THE 6th EUR. CONF. ON PYTHON IN SCIENCE (EUROSCIPY 2013) C-PyObject (mirrored or stub), if any. To deal with native PyObject s that don’t have a corresponding Java object, we utilize JyGCHead s (some minimalistic Java objects) to track them and clean them up on finalization. We use the visitproc mechanism of original CPython’s garbage collection to obtain the reference connectivity graph of all relevant native PyObject s. We mirror this connectivity in the corresponding JyGCHead s, so that the Java garbage collector marks and sweeps them according to native connectivity. A lot of care must be taken in the implementation details of this idea. For instance, it is not obvious, when to update the connectivity graph. So a design goal of the implementation is to make sure that an outdated connectivity graph can never lead to the deletion of still referenced objects. Instead, it would only delay the deletion of unreachable objects. Another issue is that the use of Java finalizers is discouraged for various reasons. An alternative to finalizers are the classes from the package java.lang.ref. We would have JyGCHead extend PhantomReference and register all of them to a ReferenceQueue. A deamon thread would be used to poll references from the queue as soon as the garbage collector enqueues them. For more details on Java reference classes see [JREF]. 7.2 Cross-Platform support We will address cross-platform support when JyNI has reached a sufficiently stable state on our development platform. At least we require rough solutions for the remaining gaps. Ideally, we focus on cross-platform support when JyNI is capable of running NumPy. 8 L ICENSE JyNI is released under the GNU [GPL] version 3. To allow for commercial use, we add the classpath exception [GPL_EXC] like known from GNU Classpath to it. We were frequently asked, why not LGPL, respectively what the difference to LGPL is. In fact, the GPL with classpath exception is less restrictive than LGPL. [GPL_EXC] states this as follows: The LGPL would additionally require you to "allow modification of the portions of the library you use". For C/C++ libraries this especially requires distribution of the compiled .o-files from the pre-linking stage. Further you would have to allow "reverse engineering (of your program and the library) for debugging such modifications". R EFERENCES [JyNI] Stefan Richthofer, Jython Native Interface (JyNI) Homepage, http://www.JyNI.org, 6 Apr. 2014, Web. 7 Apr. 2014 [JYTHON] Python Software Foundation, Corporation for National Research Initiatives, Jython: Python for the Java Platform, http: //www.jython.org, Mar. 2014, Web. 7 Apr. 2014 [IRONCLAD] Resolver Systems, Ironclad, http://code.google.com/p/ ironclad, 26 Aug. 2010, Web. 7 Apr. 2014 [CPYEXT] PyPy team, PyPy/Python compatibility, http://pypy.org/ compat.html, Web. 7 Apr. 2014 [NP4J] Joseph Cottam, NumPy4J, https://github.com/JosephCottam/ Numpy4J, 11. Dec. 2013, Web. 7 Apr. 2014 [JEPP] Mike Johnson, Java embedded Python (JEPP), http://jepp. sourceforge.net, 14 May 2013, Web. 7 Apr. 2014 [JTK] [C-API] [JREF] [GPL] [GPL_EXC] Finn Bock, jTkinter, http://jtkinter.sourceforge.net, 30 Jan. 2000, Web. 7 Apr. 2014 Python Software Foundation, Python/C API Reference Manual, http://docs.python.org/2/c-api, Web. 7 Apr. 2014 Peter Haggar, IBM Corporation, http://www.ibm.com/ developerworks/library/j-refs, 1 Oct. 2002, Web. 7 Apr. 2014 Free Software Foundation, GNU General Public License v3, http://www.gnu.org/licenses/gpl.html, 29 June 2007, Web. 7 Apr. 2014 Wikipedia, GPL linking exception, http://en.wikipedia.org/ wiki/GPL_linking_exception#The_classpath_exception, 5 Mar 2014, Web. 7 Apr. 2014
0
Modular implicits Leo White Frédéric Bour Jeremy Yallop We present modular implicits, an extension to the OCaml language for ad-hoc polymorphism inspired by Scala implicits and modular type classes. Modular implicits are based on type-directed implicit module parameters, and elaborate straightforwardly into OCaml’s first-class functors. Basing the design on OCaml’s modules leads to a system that naturally supports many features from other languages with systematic ad-hoc overloading, including inheritance, instance constraints, constructor classes and associated types. 1 Introduction A common criticism of OCaml is its lack of support for ad-hoc polymorphism. The classic example of this is OCaml’s separate addition operators for integers (+) and floating-point numbers (+.). Another example is the need for type-specific printing functions (print_int, print_string, etc.) rather than a single print function which works across multiple types. In this paper, we propose a system for ad-hoc polymorphism in OCaml based on using modules as type-directed implicit parameters. We describe the design of this system, and compare it to systems for ad-hoc polymorphism in other languages. A prototype implementation of our proposal based on OCaml 4.02.0 has been created and is available through the OPAM package manager (Section 6). 1.1 Type classes and implicits Ad-hoc polymorphism allows the dynamic semantics of a program to be affected by the types of values in that program. A program may have more than one valid typing derivation, and which one is derived when type-checking a program is an implementation detail of the type-checker. Jones et al. [10] describe the following important property: Every different valid typing derivation for a program leads to a resulting program that has the same dynamic semantics. This property is called coherence and is a fundamental property that must hold in a system for ad-hoc polymorphism. 1.1.1 Type classes Type classes in Haskell [20] have proved an effective mechanism for supporting ad-hoc polymorphism. Type classes provide a form of constrained polymorphism, allowing constraints to be placed on type variables. For example, the show function has the following type: show :: Show a = > a -> String This indicates that the type variable a can only be instantiated with types which obey the constraint Show a. These constraints are called type classes. The Show type class is defined as1 : 1 Some methods of Show have been omitted for simplicity. Kiselyov and Garrigue (Eds.): ML Family/OCaml Workshops 2014. EPTCS 198, 2015, pp. 22–63, doi:10.4204/EPTCS.198.2 c Leo White, Frédéric Bour & Jeremy Yallop This work is licensed under the Creative Commons Attribution-No Derivative Works License. Leo White, Frédéric Bour & Jeremy Yallop 23 class Show a where show :: a -> String which specifies a list of methods which must be provided in order for a type to meet the Show constraint. The method implementations for a particular type are specified by defining an instance of the type class. For example, the instance of Show for Int is defined as: instance Show Int where show = s h o w S i g n e d I n t Constraints on a function’s type can be inferred based on the use of other constrained functions in the function’s definition. For example, if a show_twice function uses the show function: s h o w _ t w i c e x = show x ++ show x then Haskell will infer that show_twice has type Show a => a -> String. Haskell’s coherence in the presence of inferred type constraints relies on type class instances being canonical – the program contains at most one instance of a type class for each type. For example, a Haskell program can only contain at most one instance of Show Int, and attempting to define two such instances will result in a compiler error. Section 4.2 describes why this property cannot hold in OCaml. Type classes are implemented using a type-directed implicit parameter-passing mechanism. Each constraint on a type is treated as a parameter containing a dictionary of the methods of the type class. The corresponding argument is implicitly inserted by the compiler using the appropriate type class instance. 1.1.2 Implicits Implicits in Scala [16] provide similar capabilities to type classes via direct support for type-directed implicit parameter passing. Parameters can be marked implicit which then allows them to be omitted from function calls. For example, a show function could be specified as: def show [ T ]( x : T )( implicit s : Showable [ T ]): String where Showable[T] is a normal Scala type defined as: trait Showable [ T ] { def show ( x : T ): String } The show function can be called just like any other: object I n t S h o w a b l e extends Showable [ Int ] { def show ( x : Int ) = x . toString } show (7)( I n t S h o w a b l e) However, the second argument can also be elided, in which case its value is selected from the set of definitions in scope which have been marked implicit. For example, if the definition of IntShowable were marked implicit: implicit object I n t S h o w a b l e extends Showable [ Int ] { def show ( x : Int ) = x . toString } then show can be called on integers without specifying the second argument – which will automatically be inserted as IntShowable because it has the required type Showable[Int]: Modular implicits 24 show (7) Unlike constraints in Haskell, Scala’s implicit parameters must always be added to a function explicitly. The need for a function to have an implicit parameter cannot be inferred from the function’s definition. Without such inference, Scala’s coherence can rely on the weaker property of non-ambiguity instead of canonicity. This means that you can define multiple implicit objects of type Showable[Int] in your program without causing an error. Instead, Scala issues an error if the resolution of an implicit parameter is ambiguous. For example, if two implicit objects of type Showable[Int] are in scope when show is applied to an Int then the compiler will report an ambiguity error. 1.1.3 Modular type classes Dreyer et al. [5] describe modular type classes, a type class system which uses ML module types as type classes and ML modules as type class instances. As with traditional type classes, type class constraints on a function can be inferred from the function’s definition. Unlike traditional type classes, modular type classes cannot ensure that type class instances are canonical (see Section 4.2). Maintaining coherence in the presence of constraint inference without canonicity requires a number of undesirable restrictions, which are discussed in Section 7.5. 1.2 Modular implicits Taking inspiration from modular type classes and implicits, we propose a system for ad-hoc polymorphism in OCaml based on passing implicit module parameters to functions based on their module type. By basing our system on implicits, where a function’s implicit parameters must be given explicitly, we are able to avoid the undesirable restrictions of modular type classes. Fig. 1 demonstrates the show example written using our proposal. The show function (line 6) has two parameters: an implicit module parameter S of module type Show, and an ordinary parameter x of type S.t. When show is applied the module parameter S does not need to be given explicitly. As with Scala implicits, when this parameter is elided the system will search the modules which have been made available for selection as implicit arguments for a module of the appropriate type. For example, on line 24, show is applied to 5. This will cause the system to search for a module of type Show with type t = int. Since Show_int is marked implicit and has the desired type, it will be used as the implicit argument of show. The Show_list module, defined on line 18, is an implicit functor – note the use of the {S : Show} syntax for its parameter rather than the usual (S : Show) used for functor arguments. This indicates that Show_list can be applied to create implicit arguments, rather than used directly as an implicit argument. For example, on line 26, show is applied to a list of integers. This causes the system to search for an implicit module of type Show with type t = int list. Such a module can be created by applying the implicit functor Show_list to the implicit module Show_int, so Show_list(Show_int) will be used as the implicit argument. Fig. 2 shows another example, illustrating how a simple library for monads might look in our proposal. The definitions of map, join and unless demonstrate our proposal’s support for higher-kinded polymorphism, analogous to constructor classes in Haskell [8]. This is a more succinct form of higherkinded polymorphism than is currently available in OCaml’s core language. Currently, higher-kinded Leo White, Frédéric Bour & Jeremy Yallop 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 module type Show = sig type t val show : t -> string end let show { S : Show } x = S . show x implicit module Show_int = struct type t = int let show x = s t r i n g _ o f _ i n t x end implicit module S h o w _ f l o a t = struct type t = float let show x = s t r i n g _ o f _ f l o a t x end implicit module S h o w _ l i s t { S : Show } = struct type t = S . t list let show x = s t r i n g _ o f _ l i s t S . show x end let () = p r i n t _ e n d l i n e ( " Show an int : " ^ show 5); p r i n t _ e n d l i n e ( " Show a float : " ^ show 1.5); p r i n t _ e n d l i n e ( " Show a list of ints : " ^ show [1; 2; 3]); Figure 1: ‘Show‘ using modular implicits 25 Modular implicits 26 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 module type Monad = sig type + ’ a t val return : ’a -> ’a t val bind : ’a t -> ( ’a -> ’b t ) -> ’b t end let return { M : Monad } x = M . return x let ( > >=) { M : Monad } m k = M . bind m k let map { M : Monad } ( m : ’a M . t ) f = m > >= fun x -> return ( f x ) let join { M : Monad } ( m : ’a M . t M . t ) = m > >= fun x -> x let unless { M : Monad } p ( m : unit M . t ) = if p then return () else m implicit module M o n a d _ o p t i o n = struct type ’a t = ’a option let return x = Some x let bind m k = match m with | None -> None | Some x -> k x end implicit module M o n a d _ l i s t = struct type ’a t = ’a list let return x = [ x ] let bind m k = List . concat ( List . map k m ) end Figure 2: ‘Monad‘ using modular implicits Leo White, Frédéric Bour & Jeremy Yallop 27 polymorphism is only supported directly using OCaml’s verbose module language or indirectly through an encoding based on defunctionalisation [22]. The calls to >>= and return in the definitions of these functions leave the module argument implicit. These cause the system to search for a module of the appropriate type. In each case, the implicit module parameter M of the function is selected because it has the appropriate type and implicit module parameters are automatically made available for selection as implicit arguments. Like Scala’s implicits, and unlike Haskell’s type classes, our proposal requires all of a function’s implicit module parameters to be explicitly declared. The map function (line 11) needs to be declared with the module parameter {M : Monad} – it could not be defined as follows: let map m f = m > >= fun x -> return ( f x ) because that would cause the system to try to resolve the implicit module arguments to >>= and return to one of the implicit modules available at the definition of map. In this case, this would result in an ambiguity error since either Monad_option or Monad_list could be used. 1.3 Contributions The contributions of this paper are as follows. • We introduce modular implicits, a design for overloading centred around type-directed instantiation of implicit module arguments, that integrates harmoniously into a language with ML-style modules (Section 2). We show how to elaborate the extended language into standard OCaml, first by explicitly instantiating every implicit argument (Section 2.2) and then by translating functions with implicit arguments into packages (Section 2.3). • The design of modular implicits involves only a small number of additions to the host language. However, the close integration with the existing module language means that modular implicits naturally support a rich array of features, from constructs present in the original type classes proposal such as instance constraints (Section 3.2) and subclasses (Section 3.3) to extensions to the original type class proposal such as constructor classes (Section 3.4), multi-parameter type classes (Section 3.5), associated types (Section 3.6) and backtracking (Section 3.7). Further, modular implicits support a number of features not available with type classes. For example, giving up canonicity – without losing the motivating benefit of coherence (Section 4) – makes it possible to support local instances (Section 3.8), and basing resolution on module type inclusion results in a system in which a single instance can be used with a variety of different signatures (Section 3.9). • Both resolution of implicit arguments and type inference involve a number of subtleties related to the interdependence of resolution and inference (Section 5.1) and compositionality (Section 5.2). We describe these at a high level here, leaving a more formal treatment to future work. • We have created a prototype implementation of our proposal based on OCaml 4.02.0. We describe some of the issues around implementing modular implicits (Section 6). • Finally, we contextualise the modular implicits design within the wide body of related work, including Haskell type classes (Section 7.1), Scala implicits (Section 7.2) canonical structures in Coq (Section 7.3), concepts in C++ (Section 7.4) and modular type classes in ML (Section 7.5). Modular implicits 28 2 The design of modular implicits We present modular implicits as an extension to the OCaml language. The OCaml module system includes a number of features, such as first-class modules and functors, which make it straightforward to elaborate modular implicits into standard OCaml. However, the design of modular implicits is not strongly tied to OCaml, and could be integrated into similar languages in the ML family. 2.1 New syntax Like several other designs for overloading based on implicit arguments, modular implicits are based on three new features. The first feature is a way to call overloaded functions. For example, we might wish to call an overloaded function show, implicitly passing a suitable value as argument, to convert an integer or a list of floating-point values to a string. The second feature is a way to abstract overloaded functions. For example, we might define a function print which calls show to turn a value into a string in order to send it to standard output, but which defers the choice of the implicit argument to pass to show to the caller of print. The third feature is a way to define values that can be used as implicit arguments to overloaded functions. For example, we might define a family of modules for building string representations for values of many different types, suitable for passing as implicit arguments to show. Figure 3 shows the new syntactic forms for modular implicits, which extend the syntax of OCaml 4.02 [13]. There is one new form for types, { M : T } -> t which makes it possible to declare show as a function with an implicit parameter S of module type Show, a second parameter of type S.t, and the return type string: val show : { S : Show } -> S . t -> string or to define + as a function with an implicit parameter N of module type Num, two further parameters of type N.t, and the return type N.t: val ( + ) : { N : Num } -> N . t -> N . t -> N . t There is a new kind of parameter for constructing functions with implicit arguments: { M : T } The following definition of show illustrates the use of implicit parameters: let show { S : Show } ( v : S . t ) = S . show v The braces around the S : Show indicate that S is an implicit module parameter of type Show. The type Show of S is a standard OCaml module type, which might be defined as in Figure 1. There is also a new kind of argument for calling functions with implicit arguments: { M } For example, the show function might be called as follows using this argument syntax: show { Show_int } 3 This is an explicitly-instantiated implicit application. Calls to show can also omit the first argument, leaving it to be supplied by a resolution procedure (described in Section 2.2): Leo White, Frédéric Bour & Jeremy Yallop 29 show 3 Implicit application requires that the function have non-module parameters after the module parameter – implicit application is indicated by providing arguments for these later parameters without providing a module argument for the module parameter. This approach simplifies type-inference and is in keeping with how OCaml handles optional arguments. It also ensures that all function applications, which may potentially perform side-effects, are syntactically function applications. There are two new declaration forms. Here is the first, which introduces an implicit module: implicit module M ({Mi : Ti })∗ = E Implicit modules serve as the implicit arguments to overloaded functions like show and +. For example, here is the definition of an implicit module Show_int with two members: a type alias t and a value member show which uses the standard OCaml function string_of_int implicit module Show_int = struct type t = int let show = s t r i n g _ o f _ i n t end Implicit modules can themselves have implicit parameters. For example, here is the definition of an implicit module Show_list with an implicit parameter which also satisfies the Show signature: implicit module S h o w _ l i s t { A : Show } = struct type t = A . t list let show l = " [ " ^ String . concat " , " ( List . map A . show l ) ^ " ] " end Implicit modules with implicit parameters are called implicit functors. Section 2.2 outlines how implicit modules are selected for use as implicit arguments. The second new declaration form brings implicit modules into scope, making them available for use in resolution: open implicit M For example, the declaration open implicit List makes every implicit module bound in the module List available to the resolution procedure in the current scope. There are also local versions of both declaration forms, which bind a module or bring implicits into scope within a single expression: let implicit module M ({Mi : Ti })∗ = E in e let open implicit M in e Implicit module declarations, like other OCaml declarations, bind names within modules, and so the signature language must be extended to support implicit module descriptions. There are two new forms for describing implicit modules in a signature: implicit module M ({Mi : Ti })∗ : T implicit module M ({Mi : Ti })∗ = M Modular implicits 30 Types typexpr ::= . . . | { module−name : module−type } -> typexpr Expressions parameter ::= . . . | { module−name : module−type } argument ::= . . . | { module−expr } expr ::= . . . | let implicit module module−name ({module−name : module−type})∗ = module−expr in expr | let open implicit module−path in expr Bindings and declarations definition ::= . . . | implicit module module−name ({module−name : module−type})∗ = module−expr | open implicit module−path Signature declarations specification ::= . . . | implicit module module−name ({module−name : module−type})∗ : module−type | implicit module module−name ({module−name : module−type})∗ = module−path Figure 3: Syntax for modular implicits The first form describes a binding for an implicit module by means of its type. For example, here is a description for the module Show_list: implicit module Show_int : Show with type t = int The second form describes a binding for an implicit module by means of an equation [6]. For example, here is a description for a module S, which is equal to Show_int implicit module S = Show_int 2.2 Resolving implicit arguments As we saw in Section 2.1, a function which accepts an implicit argument may receive that argument either implicitly or explicitly. The resolution process removes implicit arguments by replacing them with explicit arguments constructed from the modules in the implicit search space. Resolving an implicit argument M involves two steps. The first step involves gathering constraints – that is, equations on types2 within M – based on the context in which the application appears. For example, the application show 5 should generate a constraint 2 Constraints on module types and module aliases are also possible, but we leave them out of our treatment Leo White, Frédéric Bour & Jeremy Yallop 31 S . t = int on the implicit module argument S passed to show. The second step involves searching for a module which satisfies the constrained argument type. Resolving the implicit argument for the application show 5 involves searching for a module S with the type Show that also satisfies the constraint S . t = int The following sections consider these steps in more detail. 2.2.1 Generating argument constraints Generating implicit argument constraints for an application f x with an implicit argument M of type S involves building a substitution which equates each type t in S with a fresh type variable ’a, then using unification to further constrain ’a. For example, show has type: { S : Show } -> S . t -> string and the module type Show contains a single type t. The constraint generation procedure generates the constraint S . t = ’a for the implicit parameter, and refines the remainder of the type of show to ’a -> string Type-checking the application show 5 using this type reveals that ’a should be unified with int, resulting in the following constraint for the implicit parameter: S . t = int In our treatment we assume that all implicit arguments have structure types. However, functor types can also be supported by introducing similar constraints on the results of functor applications. Generating implicit argument constraints for higher-kinded types involves some additional subtleties compared to generating constraints for basic types. With higher-kinded types, type constructors cannot be directly replaced by a type variable, since OCaml does not support higher-kinded type variables. Instead, each application of a parameterised type constructor must be replaced by a separate type variable. For example, the map function has the following type: { M : Monad } -> ’a M . t -> ( ’a -> ’b ) -> ’b M . t After substituting out the module parameter, the type becomes: ’c -> ( ’a -> ’b ) -> ’d with the following constraints: ’a M . t = ’c ’b M . t = ’d Type-checking a call to map determines the type variables ’c and ’d. For example, the following call to map: Modular implicits 32 let f x = map [ x ; x ] ( fun y -> (y , y )) refines the constraints to the following: ’a M . t = ’e list ( ’ a * ’a ) M . t = ’d where ’a, ’d and ’e are all type variables representing unknown types. We might be tempted to attempt to refine the constraints further, inferring that ’a = ’e and that s M.t = s list for any type s. However, this inference is not necessarily correct. If, instead of Monad_list, the following module was in scope: implicit module M o n a d _ o d d = struct type ’a t = int list let return x = [1; 2; 3] let bind m f = [4; 5; 6] end then those inferences would be incorrect. Since the definition of the type t in Monad_odd simply discards its parameter, there is no requirement for ’e to be equal to ’a. Further, for any type s, s Monad_odd.t would be equal to int list, not to s list. In fact, inferring additional information from these constraints before performing resolution would constitute second-order unification, which is undecidable in general. Resolution does not require secondorder unification as it only searches amongst possible solutions rather than finding a most general solution. Once the constraints have been used to resolve the module argument M to Monad_list, we can safely substitute list for M.t which gives us the expected type equalities. 2.2.2 Searching for a matching module Once the module type of the implicit argument has been constrained, the next step is to find a suitable module. A module is considered suitable for use as the implicit argument if it satisfies three criteria: 1. It is constructed from the modules and functors in the implicit search space. 2. It matches the constrained module type for the implicit argument. 3. It is unique – that is, it is the only module satisfying the first two criteria. The implicit search space The implicit search space consists of those modules which have been bound with implicit module or let implicit module, or which are in scope as implicit parameters. For example, in the following code all of M, P and L are included in the implicit search space at the point of the expression show v implicit module M = M1 module N = M2 let f { P : Show } v -> let implicit module L = M3 in show v Leo White, Frédéric Bour & Jeremy Yallop 33 Furthermore, in order to avoid unnecessary ambiguity, resolution is restricted to those modules which are accessible using unqualified names. An implicit sub-module M in a module N is not in scope unless N has been opened. Implicit modules from other modules can be brought into scope using open implicit or let open implicit. Module type matching Checking that an implicit module M matches an implicit argument type involves checking that the signature of M matches the signature of the argument and that the constraints generated by type checking hold for M. As with regular OCaml modules, signature matching allows M to have more members than the argument signature. For example, the following module matches the module type Show with type t = int, despite the fact that the module has an extra value member, read: implicit module S h o w _ r e a d _ i n t = struct type t = int let show = s t r i n g _ o f _ i n t let read = i n t _ o f _ s t r i n g end Constraint matching is defined in terms of substitution: can the type variables in the generated constraint set be instantiated such that the equations in the set hold for M? For example, Monad_list meets the constraint ’a M . t = int list by replacing ’a with int, giving the valid equation int M o n a d _ l i s t. t = int list In simple cases, resolution is simply a matter of trying each implicit module in turn to see whether it matches the signature and generated constraints. However, when there are implicit functors in scope the resolution procedure becomes more involved. For example, the declaration for Show_list from Figure 1 allows modules such as Show_list(Show_int) to be used as implicit module arguments: implicit module S h o w _ l i s t { S : Show } = struct type t = S . t list let show l = s t r i n g _ o f _ l i s t S . show l end Checking whether an implicit functor can be used to create a module which satisfies an implicit argument’s constraints involves substituting an application of the functor for the implicit argument and checking that the equations hold. For example, applying Show_list to create a module M could meet the constraint: M . t = int list as substituting an application of the functor gives: S h o w _ l i s t( S ). t = int list which expands out to S . t list = int list Modular implicits 34 This generates a constraint on the argument S to Show_list: S . t = int Since Show_int satisfies this new constraint, Show_list(Show_int) meets the original constraint. Matching of candidate implicit arguments against signatures is defined in terms of OCaml’s signature matching relation, and so it supports the full OCaml signature language, including module types, functors, type definitions, exception specifications, and so on. However, since modular implicits extend the signature language with new constructs (Figure 3), the matching relation must also be extended. Matching for function types with implicit parameters is straightforward, and corresponds closely to matching for function types with labeled arguments. In particular, matching for function types does not permit elision or reordering of implicit parameters. Uniqueness In order to maintain coherence, modular implicits require the module returned by resolution to be unique. Without a uniqueness requirement the result of resolution (and hence the behaviour of the program) might depend on some incidental aspect of type-checking. To check uniqueness all possible solutions to a resolution must be considered. This requires that the search for possible resolutions terminate: if the resolution procedure does not terminate then we do not know whether there may be multiple solutions. The possibility of non-termination and the interdependence between resolution and type inference (Section 5.1) mean that checking uniqueness of solutions is incomplete, and can report ambiguity errors in cases which are not actually ambiguous. As with similar forms of incomplete inference, our proposal aims to make such cases predictable by using simple specifications of the termination conditions and of the permitted dependencies between resolution and type inference. Termination For example Implicit functors can be used multiple times whilst resolving a single implicit argument. show [ [1; 2; 3]; [4; 5; 6] ] will resolve the implicit argument of show to Show_list(Show_list(Show_int)). This means that care is needed to avoid non-termination in the resolution procedure. For example, the following functor, which tries to define how to show a type in terms of how to show that type, is obviously not well-founded: implicit module Show_it { S : Show } = struct type t = S . t let show = S . show end Type classes ensure the termination of resolution through a number of restrictions on instance declarations. However, termination of an implicit parameter resolution depends on the scope in which the resolution is performed. For this reason, the modular implicits system places restrictions on the behaviour of the resolution directly and reports an error only when a resolution which breaks these restrictions is actually attempted. When considering a module expression containing multiple applications of an implicit functor, such as the following: S h o w _ l i s t( S h o w _ l i s t( ... )) Leo White, Frédéric Bour & Jeremy Yallop 35 the system checks that the constraints that each application of the functor must meet are strictly smaller than the previous application of the functor. “Strictly smaller” is defined point-wise: all constraints must be smaller, and at least one constraint must be strictly smaller. For example, resolving an implicit module argument S of type Show with the following constraint S . t = int list list would involve considering Show_list(Show_list(T)) where T is not yet determined. The first application of Show_list would generate a constraint on its argument R: R . t = int list Thus the second application of Show_list must meet constraints which are strictly smaller than the constraints which the first application of Show_list met, and resolution can safely continue. Whereas, considering Show_it(Show_it(S)) for the same constraint, the first application of Show_it would generate a constraint on its argument R: R . t = int list list Thus the second application of Show_it must meet constraints which are the same as the constraints which the first application of Show_it met, and resolution would fail with a termination error. Multiple applications of a functor are not necessarily successive, since there may be other applications between them. For example, the expression to be checked could be of the form: S h o w _ t h i s( S h o w _ t h a t( S h o w _ t h i s( ... ))) In this case, the “strictly smaller” condition applies between the outer application of Show_this and the inner application of Show_this. The application of Show_that will not be compared to the applications of Show_this. As termination is required to check uniqueness, failure to meet the termination restrictions must be treated as an error. The system cannot simply ignore the non-terminating possibilities and continue to look for an alternative resolution. 2.3 Elaboration Once all implicit arguments in a program have been instantiated there is a phrase-by-phrase elaboration which turns each new construct into a straightforward use of existing OCaml constructs. The elaboration makes use of OCaml’s first-class modules (packages), turning functions with implicit arguments into first-class functors, Figure 4 gives the elaboration from a fully-instantiated program into implicit-free OCaml. The types of functions which accept implicit arguments { M : S } -> t become first-class functor types ( module functor ( M : S ) -> sig val value : t end ) with a functor parameter in place of the implicit parameter M and a signature with a single value member of type t in place of the return type t. (The syntax used here for the first-class functor type is not currently accepted by OCaml, which restricts the types of first-class modules to named module types, but the restriction is for historical reasons only, and so we ignore it in our treatment. The other parts of the elaboration target entirely standard OCaml.) An expression which constructs a function that accepts an implicit argument Modular implicits 36 Types The type { M : S } -> t elaborates to the package type ( module functor ( M : S ) -> sig val value : t end ) Abstractions The abstraction expression fun { M : S } -> e of type { M : S } -> t elaborates to the package expression ( module functor ( M : S ) -> struct let value = e end ) of type ( module functor ( M : S ) -> sig val value : t end )) Applications The application expression f {M} elaborates to the expression let module F = ( val f ) in let module R = F ( M ) in R . value Bindings and declarations The implicit module binding implicit module M { M1 : T1 } { M2 : T2 } . . . { Mn : Tn } = N elaborates to the expression module M ( M1 : T1 ) ( M2 : T2 ) . . . ( Mn : Tn ) = N (and similarly for local bindings and signatures). The statement open implicit M is removed from the program (and similarly for local open implicit bindings). Figure 4: Elaboration from a fully-instantiated program into OCaml Leo White, Frédéric Bour & Jeremy Yallop 37 fun { M : S } -> e becomes an expression which packs a functor ( module functor ( M : S ) -> struct let value = e end ) following the elaboration on types, turning the implicit argument into a functor argument and the body into a single value binding value. The applications of a function f to an instantiated implicit arguments M f {M} becomes an expression which unpacks f as a functor F, applies F to the module argument M, and projects the value component from the result: let module F = ( val f ) in let module R = F ( M ) in R . value Care must, of course, be taken to ensure that the name F does not collide with any of the free variables in the module expression M. Each implicit module binding implicit module M { M1 : T1 } { M2 : T2 } . . . { Mn : Tn } = N becomes under the elaboration a binding for a regular module, turning implicit parameters into functor parameters: module M ( M1 : T1 ) ( M2 : T2 ) . . . ( Mn : Tn ) = N The implicit module binding for M introduces M both into the implicit search space and the standard namespace of the program. The implicit search space is not used in the program after elaboration, and so the elaborated binding introduces M only into the standard namespace. The elaboration for local bindings and signatures is the same, mutatis mutandis. The statement open implicit M serves no purpose after elaboration, and so the elaboration simply removes it from the program. Similarly, the statement let open implicit M in e is elaborated simply to the body: e 2.4 Why target first-class functors? The elaboration from an instantiated program into first-class functors is quite simple, but the syntax of implicit arguments suggests an even simpler translation which turns each function with an implicit parameter into a function (rather than a functor) with a first-class module parameter. For example, here is the definition of show once again: Modular implicits 38 let show { S : Show } ( v : S . t ) = S . show v Under the elaboration in Figure 4 the definition of show becomes the following first-class functor binding: let show = ( functor ( S : Show ) -> struct let value = fun ( v : S . t ) -> S . show v end ) but we could instead elaborate into a function with a first-class module argument let show ( module S : Show ) ( v : S . t ) = S . show v of type ( module Show with type t = ’a ) -> ’a -> string Similarly, under the elaboration in Figure 4 the application of show to an argument show { Show_int } is translated to an expression with two local module bindings, a functor application and a projection: let module F = ( val show ) in let module R = F ( Show_int ) in R . value but under the elaboration into functions with first-class module arguments the result is a simple application of show to a packed module: show ( module Show_int ) However, the extra complexity in targeting functors rather than functions pays off in support for higher-rank and higher-kinded polymorphism. 2.4.1 Higher-rank polymorphism It is convenient to have overloaded functions be first-class citizens in the language. For example, here is a function which takes an overloaded function sh and applies it both to an integer and to a string: let s h o w _ s t u f f ( sh : { S : Show } -> S . t -> string ) = ( sh { Show_int } 3 , sh { S h o w _ s t r i n g} " hello " ) This application of the parameter sh at two different types requires sh to be polymorphic in the type S.t. This form of polymorphism, where function arguments themselves can be polymorphic functions, is sometimes called higher-rank polymorphism. The elaboration of overloaded functions into first-class functors naturally supports higher-rank polymorphism, since functors themselves can behave like polymorphic functions, with type members in their arguments. Here is the elaboration of show_stuff: let s h o w _ s t u f f ( sh : ( module functor ( S : Show ) -> sig val value : S . t -> string end )) = let module F1 = ( val sh ) in Leo White, Frédéric Bour & Jeremy Yallop 39 let module R1 = F1 ( Show_int ) in let module F2 = ( val sh ) in let module R2 = F2 ( S h o w _ s t r i n g) in ( R1 . value 5 , R2 . value " hello " ) The two functor applications F1(Show_int) and F2(Show_string) correspond to two instantiations of a polymorphic function. In contrast, if we were to elaborate overloaded functions into ordinary functions with first-class module parameters then the result of the elaboration would not be valid OCaml. Here is the result of such an elaboration: let s h o w _ s t u f f ( sh : ( module S with type t = ’a ) -> ’a -> string ) = sh ( module Show_int ) 3 ^ " " ^ sh ( module S h o w _ s t r i n g) " hello " Since sh is a regular function parameter, OCaml’s type rules assign it a monomorphic type. The function is then rejected, because sh is applied to modules of different types within the body. 2.4.2 Higher-kinded polymorphism First-class functors also provide support for higher-kinded polymorphism – that is, polymorphism in type constructors which have parameters. For example, Figure 2 defines a number of functions that are polymorphic in the monad on which they operate, such as map, which has the following type: val map : { M : Monad } -> ’a M . t -> ( ’a -> ’b ) -> ’b M . t This type is polymorphic in the parameterised type constructor M.t. Once again, elaborating overloaded functions into first-class functors naturally supports higherkinded polymorphism, since functor arguments can be used to abstract over parameterised type constructors. Here is the definition of map once again: let map { M : Monad } ( m : ’a M . t ) f = m > >= fun x -> return ( f x ) and here its its elaboration: let map = ( functor ( M : Monad ) -> struct let value = let module F_bind = ( val ( > >=)) in let module R_bind = F_bind ( M ) in let module F_ret = ( val return ) in let module R_ret = F_ret ( M ) in R_bind . value m ( fun x -> R_ret ( f x )) end ) As with higher-rank polymorphism, there is no suitable elaboration of overloaded functions involving higher-kinded polymorphism into functions with first-class module parameters, since higher-kinded polymorphism is not supported in OCaml’s core language. Modular implicits 40 2.4.3 First-class functors and type inference Type inference for higher-rank and full higher-kinded polymorphism is undecidable in the general case, and so type systems which support such polymorphism require type annotations. For instance, annotations are required on all first-class functor parameters, and on recursive definitions of recursive functors. The same requirements apply to functions with implicit module arguments. For example, the following function will not type-check if the sh parameter is not annotated with its type: let s h o w _ t h r e e sh = sh { Show_int } 3 Instead, show_three must be defined as follows: let s h o w _ t h r e e ( sh : { S : Show } -> S . t -> string ) sh { Show_int } 3 = Requiring type annotations means that type inference is not order independent – if the body of show_three were type-checked before its parameter list then inference would fail. To maintain predictability of type inference, some declarative guarantees are made about the order of type-checking; for example, a variable’s binding will always be checked before its uses. If type inference of a program only succeeds due to an ordering between operations which is not ensured by these guarantees then the OCaml compiler will issue a warning. 3 Modular implicits by example The combination of the implicit resolution mechanism and the integration with the module language leads to a system which can support a wide range of programming patterns. We demonstrate this with a selection of example programs. 3.1 Defining overloaded functions Some overloaded functions, such as show from Figure 1, simply project a member of the implicit module argument. However, it is also common to define an overloaded function in terms of an existing overloaded function. For example, the following print function composes the standard OCaml function print_string with the overloaded function show to print a value to standard output: let print { X : Show } ( v : X . t ) = p r i n t _ s t r i n g ( show v ) It is instructive to consider the details of resolution for the call to show in the body of print. As described in Section 2.2, resolution of the implicit argument S of show involves generating constraints for the types in S, unifying with the context to refine the constraints, and then searching for a module M which matches the signature of Show and satisfies the constraints. Since there is a single type t in the signature Show, resolution begins with the constraint set S . t = ’a and gives the variable show the type ’a -> string. Unification with the ascribed type of the parameter v instantiates ’a, refining the constraint Leo White, Frédéric Bour & Jeremy Yallop 41 S.t = X.t Since the type X.t is an abstract member of the implicit module parameter X, the search for a matching module returns X as the unique implicit module which satisfies the constraint. The ascription on the parameter v plays an essential role in this process. Without the ascription, resolution would involve searching for an implicit module of type Show satisfying the constraint S.t = ’a. Since any implicit module matching the signature Show satisfies this constraint, regardless of the definition of t, the resolution procedure will fail with an ambiguity error if there are multiple implicit modules in scope matching Show. 3.2 Instance constraints Haskell’s instance constraints make it possible to restrict the set of instantiations of type parameters when defining overloaded functions. For example, here is an instance of the Show class for the pair constructor (,), which is only available when there are also an instance of Show for the type parameters a and b: instance ( Show a , Show b ) = > Show (a , b ) where show (x , y ) = " ( " ++ show x ++ " ," ++ show y ++ " ) " With modular implicits, instance constraints become parameters to implicit functor bindings: implicit module S h o w _ p a i r { A : Show } { B : Show } = struct type t = A . t * B . t let show (x , y ) = " ( " ^ A . show x ^ " ," ^ B . show y ^ " ) " end It is common for the types of implicit functor parameters to be related to the type of the whole, as in this example, where the parameters each match Show and the result has type Show with type t = A.t * B.t. However, neither instance constraints nor implicit module parameters require that the parameter and the result types are related. Here is the definition of an implicit module Complex_cartesian, which requires only that the parameters have implicit module bindings of type Num, not of type Complex: implicit module C o m p l e x _ c a r t e s i a n { N : Num } = struct type t = N . t c o m p l e x _ c a r t e s i a n let conj { re ; im } = { re ; im = N . negate im } end (We leave the reader to deduce the definitions of the complex_cartesian type and of the Num signature.) 3.3 Inheritance Type classes in Haskell provide support for inheritance. For example, the Ord type class is defined as inheriting from the Eq type class: class Eq a where (==) :: a -> a -> Bool class Eq a = > Ord a where compare :: a -> a -> Ordering Modular implicits 42 This means that instances of Ord can only be created for types which have an instance of Eq. By declaring Ord as inheriting from Eq, functions can use both == and compare on a type with a single constraint that the type have an Ord instance. 3.3.1 The “diamond” problem It is tempting to try to implement inheritance with modular implicits by using the structural subtyping provided by OCaml’s modules. For example, one might try to define Ord and Eq as follows: module type Eq = sig type t val equal : t -> t -> bool end let equal { E : Eq } x y = E . equal x y module type Ord = sig type t val equal : t -> t -> bool val compare : t -> t -> int end let compare { O : Ord } x y = O . compare x y which ensures that any module which can be used as an implicit Ord argument can also be used as an implicit Eq argument. For example, a single module can be created for both equality and comparison of integers: implicit module Ord_int = struct type t = int let equal = Int . equal let compare = Int . compare end However, an issue arises when trying to implement implicit functors for type constructors using this scheme. For example, we might want to define the following two implicit functors: implicit module Eq_list { E : Eq } = struct type t = E . t list let equal x y = List . equal E . equal x y end implicit module Ord_list { O : Ord } = struct type t = O . t list let equal x y = List . equal O . equal x y let compare x y = List . compare O . compare x y end which implement Eq for lists of types which implement Eq, and implement Ord for lists of types which implement Ord. Leo White, Frédéric Bour & Jeremy Yallop 43 The issue arises when we wish to resolve an Eq instance for a list of a type which implements Ord. For example, we might wish to apply the equal function to lists of ints: equal [1; 2; 3] [4; 5; 6] The implicit argument in this call is ambiguous: we can use either Eq_list(Ord_int) or Ord_list(Ord_int). This is a kind of “diamond” problem: we can restrict Ord_int to an Eq and then lift it using Eq_list, or we can lift Ord_int using Ord_list and then restrict the result to an Eq. In Haskell, the problem is avoided by canonicity – it doesn’t matter which way around the diamond we go, we know that the result will be the same. 3.3.2 Module aliases OCaml provides special support for module aliases [6]. A module can be defined as an alias for another module: module L = List This defines a new module whose type is the singleton type “= List”. In other words, the type of L guarantees that it is equal to List. This equality allows types such as Set(List).t and Set(L).t to be considered equal. Since L is statically known to be equal to List, we do not consider an implicit argument to be ambiguous if L and List are the only possible choices. In our proposal we extend module aliases to support implicit functors. For example, implicit module Show_l { S : Show } = S h o w _ l i s t{ S } creates a module alias. This means that Show_l(Show_int) is an alias for Show_list(Show_int), and its type guarantees that the two modules are equal. In order to maintain coherence we must require that all implicit functors be pure. If Show_list performed side-effects then two separate applications of it would not necessarily be equal. We ensure this using the standard OCaml value restriction. This is a very conservative approximation of purity, but we do not expect it to be too restrictive in practice. 3.3.3 Inheritance with module aliases Using module aliases we can implement inheritance using modular implicits. Our Ord example is encoded as follow: module type Eq = sig type t val equal : t -> t -> bool end let equal { E : Eq } x y = E . equal x y module type Ord = sig type t module Eq : Eq with type t = t Modular implicits 44 val compare : t -> t -> int end let compare { O : Ord } x y = O . compare x y implicit module Eq_ord { O : Ord } = O . Eq implicit module Eq_int = struct type t = int let equal = Int . equal end implicit module Ord_int = struct type t = int module Eq = Eq_int let compare = Int . compare end implicit module Eq_list { E : Eq } = struct type t = E . t list let equal x y = List . equal E . equal x y end implicit module Ord_list { O : Ord } = struct type t = O . t list module Eq = Eq_list { O . Eq } let compare x y = List . compare O . compare x y end The basic idea is to represent inheritance by including a submodule of the inherited type, along with an implicit functor to extract that submodule. By wrapping the inherited components in a module they can be aliased. The two sides of the “diamond” are now Eq_list(Eq_ord(Ord_int)) or Eq_ord(Ord_list(Ord_int)), both of which are aliases for Eq_list(Eq_int) so there is no ambiguity. 3.4 Constructor classes Since OCaml’s modules support type members which have type parameters, modular implicits naturally support constructor classes [8] – i.e. functions whose implicit instances are indexed by parameterised type constructors. For example, here is a definition of a Functor module type, together with implicit instances for the parameterised types list and option: module type Functor = sig type + ’ a t val map : ( ’ a -> ’b ) -> ’a t -> ’b t end Leo White, Frédéric Bour & Jeremy Yallop 45 let map { F : Functor } ( f : ’a -> ’b ) ( c : ’a F . t ) = F . map f c implicit module F u n c t o r _ l i s t = struct type ’a t = ’a list let map = List . map end implicit module F u n c t o r _ o p t i o n = struct type ’a t = ’a option let map f = function None -> None | Some x -> Some ( F x ) end The choice to translate implicits into first-class functors makes elaboration for implicit modules with parameterised types straightforward. Here is the elaborated code for map: let map = ( module functor ( F : Functor ) -> struct let value ( f : ’a -> ’b ) ( c : ’a F . t ) = F . map f c end ) 3.5 Multi-parameter type classes Most of the examples we have seen so far involve resolution of implicit modules with a single type member. However, nothing in the design of modular implicits restricts resolution to a single type. The module signature inclusion relation on which resolution is based supports modules with an arbitrary number of type members (and indeed, with many other components, such as modules and module types). Here is an example illustrating overloading with multiple types. The Widen signature includes two type members, slim and wide, and a coercion function widen for converting from the former to the latter. The two implicit modules, Widen_int_float and Widen_opt, respectively implement conversion from a ints to floats, and lifting of widening to options. The final line illustrates the instantiation of a widening function from int option to float option, based on the three implicit modules. module type Widen = sig type slim type wide val widen : slim -> wide end let widen { C : Widen } ( v : C . slim ) : C . wide = C . widen v implicit module W i d e n _ i n t _ f l o a t = struct type slim = int type wide = float let widen = P e r v a s i v e s. float Modular implicits 46 end implicit module W i d e n _ o p t{ A : Widen } = struct type slim = A . slim option type wide = A . wide option let widen = function None -> None | Some v -> Some ( A . widen v ) end let v : float option = widen ( Some 3) In order to find a suitable implicit argument C for the call to widen on the last line, the resolution procedure first generates fresh types variables for C.slim and C.wide C . slim = ’a C . wide = ’b and replaces the corresponding names in the type of the variable widen: widen : ’a -> ’b Unifying this last type with the type supplied by the context (i.e. the type of the argument and the ascribed result type) reveals that ’a should be equal to int option and ’b should be equal to float option. The search for a suitable argument must therefore find a module of type Widen with the following constraints: C . slim = int option C . wide = float option The implicit functor Widen_option is suitable if a modules A can be found such that A has type Widen with the constraints C . slim = int C . wide = float The implicit module Widen_int_float satisfies these constraints, and the search is complete. The instantiated call shows the implicit module argument constructed by the resolution procedure: let v : float option = widen { W i d e n _ o p t i o n( W i d e n _ i n t _ f l o a t )} ( Some 3) 3.6 Associated types Since OCaml modules can contain abstract types, searches can be existentially quantified. For example, we can ask for a type which can be shown Show rather than how to show a specific type Show with type t = int Leo White, Frédéric Bour & Jeremy Yallop 47 The combination of signatures with multiple type members and support for existential searches gives us similar features to Haskell’s associated types [1]. We can search for a module based on a subset of the types it contains and the search will fill-in the remaining types for us. For example, here is a module type Array for arrays with a type t of arrays and a type elem of array elements, together with a function create for creating arrays: module type Array = sig type t type elem [...] end val create : { A : Array } -> int -> A . elem -> A . t The create function can be used without specifying the array type being created: let x = create 5 true This will search for an implicit Array with type elem = bool. When one is found x will correctly be given the associated t type. This allows different array types to be used for different element types. For example, arrays of bools could be implemented as bit vectors, and arrays of ints implemented using regular OCaml arrays by placing the following declarations in scope: implicit module B o o l _ a r r a y = B i t _ v e c t o r implicit module I n t _ a r r a y = Array ( Int ) 3.7 Backtracking Haskell’s type class system ignores instance constraints when determining whether two instances are ambiguous. For example, the following two instance constraints are always considered ambiguous: instance Floating n = > Complex ( C o m p l e x _ c a r t e s i a n n ) instance Integral n = > Complex ( C o m p l e x _ c a r t e s i a n n ) In contrast, our system only considers those implicit functors for which suitable arguments are in scope as candidates for instantiation. For example, the following two implicit functors are not inherently ambiguous: implicit module C o m p l e x _ c a r t s i a n _ f l o a t i n g { N : Floating } : Complex with type t = N . t c o m p l e x _ c a r t e s i a n implicit module C o m p l e x _ c a r t s i a n _ i n t e g r a l { N : Integral } : Complex with type t = N . t c o m p l e x _ c a r t e s i a n The Complex_cartesian_floating and Complex_cartesian_integral modules only give rise to ambiguity if constraint generation (Section 2.2.1) determines that the type t of the Complex signature should be instantiated to s complex_cartesian where there are instances of both Floating and Integral in scope for s: implicit module F l o a t i n g _ s : Floating with type t = s implicit module I n t e g r a l _ s : Integral with type t = s Modular implicits 48 Taking functor arguments into account during resolution is a form of backtracking. The resolution procedure considers both Complex_cartesian_integral and Complex_cartesian_floating as candidates for instantiation and attempts to find suitable arguments for both. The resolution is only ambiguous if both implicit functors can be applied to give implicit modules of the appropriate type. 3.8 Local instances The let implicit construct described in Section 2.1 makes it possible to define implicit modules whose scope is limited to a particular expression. The following example illustrates how these local implicit modules can be used to select alternative behaviours when calling overloaded functions. Here is a signature Ord, for types which support comparison: module type Ord = sig type t val cmp : t -> t -> int end The Ord signature makes a suitable type for the implicit argument of a sort function: val sort : { O : Ord } -> O . t list -> O . t list Each call to sort constructs a suitable value for Ord from the implicit modules and functors in scope. Two possible orderings for int are: module Ord_int = struct type t = int let cmp l r = P e r v a s i v e s. compare l r end module O r d _ i n t _ r e v = struct type t = int let cmp l r = P e r v a s i v e s. compare r l end Either ordering can be used with sort by passing the argument explicitly: sort { Ord_int } items or sort { O r d _ i n t _ r e v} items Explicitly passing implicit arguments bypasses the resolution mechanism altogether. It is occasionally useful to combine overriding of implicit modules for particular types with automatic resolution for other types. For example, if the following implicit module definition is in scope then sort can be used to sort lists of pairs of integers: implicit module Ord_pair { A : Ord } { B : Ord } = struct type t = A . t * B . t let cmp ( x1 , x2 ) ( y1 , y2 ) = let c = A . cmp x1 y1 in if c <> 0 then c else B . cmp x2 y2 end Leo White, Frédéric Bour & Jeremy Yallop 49 Suppose that we want to use Ord_pair together with both the regular and reversed integer comparisons to sort a list of pairs. One approach is to construct and pass entire implicit arguments explicitly: sort { Ord_pair ( I n t _ o r d _ r e v )( I n t _ o r d _ r e v )} items Alternatively (and equivalently), local implicit module bindings for Ord and Ord_int_rev make it possible to override the behaviour at ints while using the automatic resolution behaviour to locate and use the Ord_pair functor: let s o r t _ b o t h _ w a y s ( items : ( int * int ) list ) = let ord = let implicit module Ord = Ord_int in sort items in let rev = let implicit module Ord = O r d _ i n t _ r e v in sort items in ord , rev In Haskell, which lacks both local instances and a way of explicitly instantiating type class dictionary arguments, neither option is available, and programmers are advised to define library functions in pairs, with one function (such as sort) that uses type classes to instantiate arguments automatically, and one function (such as sortBy) that accepts a regular argument in place of a dictionary: sort :: Ord a = > [ a ] -> [ a ] sortBy :: ( a -> a -> Ordering ) -> [ a ] -> [ a ] 3.9 Structural matching As Section 2.2.2 explains, picking a suitable implicit argument involves a module which matches a constrained signature. In contrast to Haskell’s type classes, matching is therefore defined structurally (in terms of the names and types of module components) rather than nominally (in terms of the name of the signature). Structural matching allows the caller of an overloaded function to determine which part of a signature is required rather than requiring the definer of a class to anticipate which overloaded functions are most suitable for grouping together. It is not difficult to find situations where structural matching is useful. The following signature describes types which support basic arithmetic, with members for zero and one, and for addition and subtraction: module type Num = sig type t val zero : t val one : t val ( + ) : t -> t -> t val ( * ) : t -> t -> t end The following implicit modules implement Num for the types int and float, using functions from OCaml’s standard library: Modular implicits 50 implicit module Num_int = struct type t = int let zero = 0 let one = 1 let ( + ) = P e r v a s i v e s .( + ) let ( * ) = P e r v a s i v e s .( * ) end implicit module N u m _ f l o a t = struct type t = float let zero = 0.0 let one = 1.0 let ( + ) = P e r v a s i v e s .( +. ) let ( * ) = P e r v a s i v e s .( *. ) end The Num signature makes it possible to define a variety of arithmetic functions. However, in some cases Num offers more than necessary. For example, defining an overloaded function sum to compute the sum of a list of values requires only zero and +, not one and *. Using Num as the implicit signature for sum would make unnecessarily exclude types (such as strings) which have a notion of addition but which do not support multiplication. Defining more constrained signatures makes it possible to define more general functions. Here is a signature Add which includes only those elements of Num involved in addition: module type Add = sig type t val zero : t val ( + ) : t -> t -> t end Using Add we can define a sum which works for any type that has an implicit module with definitions of zero and plus: let sum { A : Add } ( l : A . t list ) = List . f o l d _ l e f t A .( + ) A . zero l The existing implicit modules Num_int and Num_float can be used with sum, since they both match Add. The following module, Add_string, also matches Add, making it possible to use sum either for summing a list of numbers or for concatenating a list of strings: implicit module A d d _ s t r i n g = struct type t = string let zero = " " let ( + ) = P e r v a s i v e s .( ^ ) (* c o n c a t e n a t i o n *) end In other cases it may be necessary to use some other part of the Num interface. The following function computes an inner product for any type with an implicit module that matches Num: let dot { N : Num } ( l1 : N . t list ) ( l2 : N . t list ) = sum ( List . map2 N .( * ) l1 l2 ) Leo White, Frédéric Bour & Jeremy Yallop 51 This time it would not be sufficient to use Add for the type of the implicit argument, since dot uses both multiplication and addition. However, Add still has a role to play: the implicit argument of sum uses the implicit argument N with type Add. Since the Num signature is a subtype of Add according to the rules of OCaml’s module system, the argument can be passed through directly to sum. Here is the elaboration of dot, showing how the sum functor being unpacked, bound to F, then applied to the implicit argument N: let dot = ( module functor ( N : Num ) -> struct let value ( l1 : N . t list ) ( l2 : N . t list ) = let module F = ( val sum ) in let module R = F ( N ) in R . value ( List . map2 N .( * ) l1 l2 ) end ) An optimising compiler might lift the unpacking and application of sum outside the body of the function, in order to avoid repeating the work each time the list arguments are supplied. Section 3.3 illustrated that structural matching is not an ideal encoding for full class inheritance hierarchies due to the diamond problem. However, it can provide a more lightweight encoding for simple forms of inheritance. 4 Canonicity In Haskell, a type class has at most one instance per type within a program. For example, defining two instances of Show for the type Int or for the type constructor Maybe is not permitted. We call this property canonicity. Haskell relies on canonicity to maintain coherence, whereas canonicity cannot be preserved by our system due to OCaml’s support for modular abstraction. 4.1 Inference, coherence and canonicity A key distinction between type classes and implicits is that, with type classes, constraints on a function’s type can be inferred based on the use of other constrained functions in the function’s definitions. For example, if a show_twice function uses the show function: s h o w _ t w i c e x = show x ++ show x then Haskell will infer that show_twice has type Show a => a -> String. This inference raises issues for coherence in languages with type classes. For example, suppose we have the following instance: instance Show a = > Show [ a ] where show l = s h o w _ l i s t l and consider the function: s h o w _ a s _ l i s t x = show [ x ] There are two valid types which could be inferred for this function: s h o w _ a s _ l i s t :: Show [ a ] = > a -> String Modular implicits 52 or s h o w _ a s _ l i s t :: Show a = > a -> String In the second case, the Show [a] instance has been used to reduce the constraint to Show a. The choice between these two types changes where the Show [a] constraint is resolved. In the first case it will be resolved at calls to show_as_list. In the second case it has been resolved at the definition of show_as_list. If type class instances are canonical then it does not matter where a constraint is resolved, as there is only a single instance to which it could be resolved. Thus, with canonicity, the inference of show_as_list’s type cannot affect the dynamic semantics of the program, and coherence is preserved. However, if type class instances are not canonical then where a constraint is resolved can affect which instance is chosen, which in turn changes the dynamic semantics of the program. Thus, without canonicity, the inference of show_as_list’s type can affect the dynamic semantics of the program, breaking coherence. 4.2 Canonicity and abstraction It would not be possible to preserve canonicity in OCaml because type aliases can be made abstract. Consider the following example: module F ( X : Show ) = struct implicit module S = X end implicit module Show_int = struct type t = int let show = s t r i n g _ o f _ i n t end module M = struct type t = int let show _ = " An int " end module N = F ( M ) The functor F defines an implicit Show module for the abstract type X.t, whilst the implicit module Show_int is for the type int. However, F is later applied to a module where t is an alias for int. This violates canonicity but this violation is hidden by abstraction. Whilst it may seem that such cases can be detected by peering through abstractions, this is not possible in general and defeats the entire purpose of abstraction. Fundamentally, canonicity is not a modular property and cannot be respected by a language with full support for modular abstraction. 4.3 Canonicity as a feature Besides maintaining coherence, canonicity is sometimes a useful feature in itself. The canonical example for the usefulness of canonicity is the union function for sets in Haskell. The Ord type class defines an Leo White, Frédéric Bour & Jeremy Yallop 53 ordering for a type3 : class Ord a where ( <=) :: a -> a -> Bool This ordering is used to create sets implemented as binary trees: data Set a empty :: Set a insert :: Ord a = > a -> Set a -> Set a delete :: Ord a = > a -> Set a -> Set a The union function computes the union of two sets: union :: Ord a = > Set a -> Set a -> Set a Efficiently implementing this union requires both sets to have been created using the same ordering. This property is ensured by canonicity, since there is only one instance of Ord a for each a, and all sets of type Set a must have been created using it. 4.4 An alternative to canonicity as a feature In terms of modular implicits, Haskell’s union function would have type: val union : { O : Ord } -> O . t set -> O . t set -> O . t set but without canonicity it is not safe to give union this type since there is no guarantee that all sets of a given type were created using the same ordering. The issue is that the set type is only parametrised by the type of its elements, when it should really be also parametrised by the ordering used to create it. Traditionally, this problem is solved in OCaml by using applicative functors: module Set ( O : Ord ) : sig type elt type t val empty : t val add : elt -> t -> t val remove : elt -> t -> t val union : t -> t -> t [...] end When applied to an Ord argument O, the Set functor produces a module containing the following functions: val val val val empty : Set ( O ). t add : elt -> Set ( O ). t -> Set ( O ). t remove : elt -> Set ( O ). t -> Set ( O ). t union : Set ( O ). t -> Set ( O ). t -> Set ( O ). t The same approach transfers to modular implicits, giving our polymorphic set operations the following types: 3 Some details of Ord are omitted for simplicity Modular implicits 54 val val val val empty : { O : Ord } -> Set ( O ). t add : { O : Ord } -> O . t -> Set ( O ). t -> Set ( O ). t remove : { O : Ord } -> O . t -> Set ( O ). t -> Set ( O ). t union : { O : Ord } -> Set ( O ). t -> Set ( O ). t -> Set ( O ). t The type for sets is now Set(O).t which is parametrised by the ordering module O, ensuring that union is only applied to sets created using the same ordering. 5 Order independence and compositionality Two properties enjoyed by traditional ML type systems are order independence and compositionality. This section describes how modular implicits affect these properties. 5.1 Order independence Type inference is order independent when the order in which expressions are type-checked does not affect whether type inference succeeds. Traditional ML type inference is order independent, however some of OCaml’s advanced features, including first-class functors, cause order dependence. As described in Section 2.2, type checking implicit applications has two aspects: 1. Inferring the types which constrain the implicit argument 2. Resolving the implicit argument using the modules and functors in the implicit scope. These two aspects are interdependent: the order in which they are performed affects whether type inference succeeds. 5.1.1 Resolution depends on types Consider the implicit application from line 24 of our Show example (Figure 1): show 5 Resolving the implicit argument S requires first generating the constraint S.t = int. Without this constraint the argument would be ambiguous – it could be Show_int, Show_float, Show_list(Show_float), etc. This constraint can only come from type-checking the non-implicit argument 5. This demonstrates that resolution depends on type inference, and so some type inference must be done before implicit arguments are resolved. 5.1.2 Types depend on resolution Given that resolution depends on type inference, we might be tempted to perform resolution in a second pass of the program, after all type inference has finished. However, although it is not immediately obvious, types also depend on resolution. Consider the following code: Leo White, Frédéric Bour & Jeremy Yallop 55 module type Sqrtable = sig type t val sqrt : t -> t end let sqrt { S : Sqrtable } x = S . sqrt x implicit module S q r t _ f l o a t = struct type t = float let sqrt x = s q r t _ f l o a t x end let s q r t _ t w i c e x = sqrt ( sqrt x ) The sqrt_twice function contains two calls to sqrt, which has an implicit argument of module type Sqrtable. There are no constraints on these implicit parameters as x has an unknown type; however, there is only one Sqrtable module in scope so the resolution is still unambiguous. By resolving S to Sqrt_float we learn that x in fact has type float. This demonstrates that types depend on resolution, and so resolution must be done before some type inference. In particular, it is important that resolution is performed before generalisation is attempted on any types which depend on resolution because type variables cannot be unified after they have been generalised. 5.1.3 Resolution depends on resolution Since resolution depends on types, and types can depend on resolution, it follows that one argument’s resolution can depend on another argument’s resolution. Following on from the previous example, consider the following code: module type Summable = sig type t val sum : t -> t -> t end let double { S : Summable } x = S . sum x x implicit module Sum_int = struct type t = int let sum x y = x + y end implicit module S u m _ f l o a t = struct type t = float let sum x y = x +. y end let s q r t _ d o u b l e x = sqrt ( double x ) Modular implicits 56 Here there are two implicit applications: one of sqrt and one of double. As before, the arguments of these functions have no constraints since x’s type is unknown. If the resolution of double’s implicit argument is attempted without constraint it will fail as ambiguous, since either Sum_int or Sum_float could be used. However, if sqrt’s implicit argument is first resolved to Sqrt_float then we learn that the return type of the call to double is float. This allows double’s implicit argument to unambiguously be resolved as Sum_float. This demonstrates that resolutions can depend on other resolutions, and so the order in which resolutions are attempted will affect which programs will type-check successfully. 5.1.4 Predictable inference In the presence of order dependence, inference can be kept predictable by providing some declarative guarantees about the order of type-checking, and disallowing programs whose type inference would only succeed due to an ordering between operations which is not ensured by these guarantees. This is the approach OCaml takes with its other order-dependent features4 . Taking the same approach with modular implicits involves two choices about the design: 1. When should implicit resolution happen relative to type inference? 2. In what order should implicit arguments be resolved? The dependence of resolution on type inference is much stronger than the dependence of type inference on resolution: delaying type inference until after resolution would lead to most argument resolutions being ambiguous. In order to perform as much inference as possible before attempting resolution, resolution is delayed until the point of generalisation. Technically, resolution could be delayed until a generalisation is reached which directly depends on a type involved in that resolution. However, we take a more predictable approach and resolve all the implicit arguments in an expression whenever the result of that expression is generalised. In practice, this means that implicit arguments are resolved at the nearest enclosing let binding. For example, in this code: let f g x = let z = [ g ( show 5) ( show 4.5); x ] in g x :: z the implicit arguments of both calls to show will be resolved after the entire expression [ g ( show 5) ( show 4.5); x ] has been type-checked, but before the expression g x :: z has been type-checked. Our implementation of modular implicits makes very few guarantees about the order of resolution of implicit arguments within a given expression. It is guaranteed that implicit arguments of the same function will be resolved left-to-right, and that implicit arguments to a function will be resolved before any implicit arguments within other arguments to that function. These guarantees mean that the example of dependent resolutions: 4 OCaml emits a warning rather than out-right disallowing programs which depend on an unspecified ordering Leo White, Frédéric Bour & Jeremy Yallop 57 let s q r t _ d o u b l e x = sqrt ( double x ) will resolve without ambiguity, but that the similar expression: let d o u b l e _ s q r t x = double ( sqrt x ) will result in an ambiguous resolution error. This can be remedied either by adding a type annotation: let d o u b l e _ s q r t x : float = double ( sqrt x ) or by lifting the argument into its own let expression to force its resolution: let d o u b l e _ s q r t x = let s = sqrt x in double s Another possibility would be to try each implicit argument being resolved in turn until an unambiguous one is found. Resolving that argument might produce more typing information allowing further arguments to be resolved unambiguously. This approach is analogous to using a breadth-first resolution strategy in logic programming, rather than a depth-first strategy: it improves the completeness of the search – and so improves the predictability of inference – but is potentially less efficient in practice. Comparing this approach with the one used in our existing implementation is left for future work. 5.2 Compositionality Compositionality refers to the ability to combine two independent well-typed program fragments to produce a program fragment that is also well typed. In OCaml, this property holds of top-level definitions up to renaming of identifiers. Requiring that implicit arguments be unambiguous means that renaming of identifiers is no longer sufficient to guarantee two sets of top-level definitions can be composed. For example, implicit module S h o w _ i n t 1 = struct type t = int let show x = " S h o w _ i n t 1: " ^ ( i n t _ o f _ s t r i n g x ) end let x = show 5 and implicit module S h o w _ i n t 2 = struct type t = int let show x = " S h o w _ i n t 2: " ^ ( i n t _ o f _ s t r i n g x ) end let y = show 6 cannot be safely combined because the call to show in the definition of y would become ambiguous. In order to ensure that two sets of definitions can safely compose they must not contain overlapping implicit module declarations. However, whilst compositionality of top-level definitions is lost, compositionality of modules is maintained. Any two well-typed module definitions can be combined to produce a well-typed program. This is an important property, as it allows support for separate compilation without the possibility of errors at link time. Modular implicits 58 6 Implementation We have created a prototype implementation of our proposal based on OCaml 4.02.0, which can be installed through the OPAM package manager: opam switch 4.02.0+ modular - i m p l i c i t s Although it is not yet in a production ready state, the prototype has allowed us to experiment with the design and to construct examples like those in Section 3. We have also used the prototype to build a port of Haskell’s Scrap Your Boilerplate [12] library, which involves aroud 600 lines of code, and exercises many of the features and programming patterns described in this paper, including inheritance, higherorder polymorphism, implicit functors and constructor classes. As the prototype becomes more stable we hope to use it to explore the viability of modular implicits at greater scale. One key concern when implementing modular implicits is the efficiency of the resolution procedure. Whilst the changes to OCaml’s type inference required for modular implicits are small and should not affect its efficiency, the addition of a resolution for every use of functions with implicit parameters could potentially have a dramatic effect on performance. Our prototype implementation takes a very naive approach to resolution, keeping a list of the implicit modules and functors in scope, and checking each of them as a potential solution using OCaml’s existing procedure for checking module inclusion. The performance of resolution could be improved in the following ways: Memoization Resolutions can be memoized so that repeated uses of the same functions with implicit arguments do not cause repeated full resolutions. Even if new implicit modules are added to the environment it is possible to partially reuse the results of previous resolutions since module expressions which do not involve the new modules do not need to be reconsidered. Indexing A mapping can be maintained between module types and the implicit modules which could be used to resolve them to avoid searching over the whole list of implicit modules in scope. In particular, indexing based on the names of the members of the module type is simple to implement and should quickly reduce the number of implicit modules that need to be considered for a particular resolution. Fail-fast module inclusion Checking module inclusion in OCaml is an expensive operation. However, during resolution most inclusion checks are expected to fail. Using an implementation of module inclusion checking which is optimised for the failing case would make it possible to quickly eliminate most potential solutions to a resolution. These techniques aim to reduce the majority of resolutions to a few table lookups, which should allow modular implicits to scale effectively to large code bases with many implicit declarations and implicit arguments. However, we leave the implementation and full evaluation of these techniques to future work. 7 Related work There is a large literature on systematic approaches to ad-hoc polymorphism, Kaes [11] being perhaps the earliest example. We restrict our attention here to a representative sample. Leo White, Frédéric Bour & Jeremy Yallop 59 7.1 Type classes Haskell type classes [20] are the classic formalised method for ad-hoc polymorphism. They have been replicated in a number of other programming languages (e.g. Agda’s instance arguments [3], Rust’s traits [15]). The key difference between approaches based on type class and approaches based on implicits is that type class constraints can be inferred, whilst implicit parameters must be defined explicitly. Haskell maintains coherence, in the presence of such inference, by ensuring that type class instances are canonical. Canonicity is not possible in a language which supports modular abstraction (such as OCaml), and so type classes are not always a viable choice. Canonicity is also not always desirable: the restriction to a single instance per type is not compositional and can force users to create additional types to work around it. Consequently, some proposals for extensions to type classes involve relinquishing canonicity in order to support desirable features such as local instances [4]. The decision to infer constraints also influences other design choices. For example, whereas modular implicits instantiate implicit arguments only at function application sites, the designers of type classes take the dual approach of only generalizing constrained type variables at function abstraction sites [9, Section 4.5.5]. Both restrictions have the motivation of avoiding unexpected work – in Haskell, adding constraints to non-function bindings can cause a loss of sharing, whereas in OCaml, inserting implicit arguments at sites other than function calls could cause side effects to take place in the evaluation of apparently effect-free code. Modular implicits offer a number of other advantages over type classes, including support for backtracking during parameter resolution, allowing for more precise detection of ambiguity, and resolution based on any type defined within the module rather than on a single specific type. However, there are also some features of type classes that our proposal does not support, such as the ability to instantiate an instance variable with an open type expression; in Haskell one can define the following instance, which makes it possible to show values of type T a for any a: instance Show ( T a ) 7.2 Implicits Scala implicits [16] are a major inspiration for this work. They provide implicit parameters on functions, which are selected from the scope of the call site based on their type. In Scala these parameters have ordinary Scala types, whilst we propose using module types. Scala’s object system has many properties in common with a module system, so advanced features such as associated types are still possible despite Scala’s implicits being based on ordinary types. Scala’s implicits have a more complicated notion of scope than our proposal. This seems to be aimed at fitting implicits into Scala’s object-oriented approach: for example allowing implicits to be searched for in companion objects of the class of the implicit parameter. This makes it more difficult to answer the question “Where is the implicit parameter coming from?”, in turn making it more difficult to reason about code. Our proposal simply uses lexical scope when searching for an implicit parameter. Scala supports overlapping implicit instances. If an implicit parameter is resolved to more than one definition, rather than give an ambiguity error, a complex set of rules gives an ordering between definitions, and a most specific definition will be selected. An ambiguity error is only given if multiple definitions are considered equally specific. This can be useful, but makes reasoning about implicit pa- Modular implicits 60 rameters more difficult: to know which definition is selected you must know all the definitions in the current scope. Our proposal always gives an ambiguity error if multiple implicit modules are available. In addition to implicit parameters, Scala also supports implicit conversions. If a method is not available on an object’s type the implicit scope is searched for a function to convert the object to a type on which the method is available. This feature greatly increases the complexity of finding a method’s definition, and is not supported in our proposal. Chambart et al. have proposed [2] adding support for implicits to OCaml using core OCaml types for implicit parameters. Our proposal instead uses module types for implicit parameters. This allows our system to support more advanced features including associated types and higher kinds. The module system also seems a more natural fit for ad-hoc polymorphism due to its direct support for signatures. The implicit calculus [17] provides a minimal and general calculus of implicits which could serve as a basis for formalising many aspects of our proposal. Coq’s type classes [18] are similar to implicits. They provide implicit dependent record parameters selected based on their type. 7.3 Canonical structures In addition to type classes, Coq also supports a mechanism for ad-hoc polymorphism called canonical structures [14]. Type classes and implicits provide a mechanism to resolve a value based on type information. Coq, being dependently typed, already uses unification to resolve values from type information, so canonical structures support ad-hoc polymorphism by providing additional ad-hoc rules that are applied during unification. Like implicits, canonical structures do not require canonicity, and do not operate on a single specific type: ad-hoc unification rules are created for every type or term defined in the structure. Canonical structures also support backtracking of their search due to the backtracking built into Coq’s unification. 7.4 Concepts Gregor et al. [7] describe concepts, a system for ad-hoc polymorphism in C++5 . C++ has traditionally used simple overloading to support ad-hoc polymorphism restricted to monomorphic uses. C++ also supports parametric polymorphism through templates. However, overloading within templates is re-resolved after template instantiation. This means that the combination of overloading and templates provides full ad-hoc polymorphism. Delaying a significant part of type checking until template instantiation increases compilation times and makes error message more difficult to understand. Concepts provide a disciplined mechanism for full ad-hoc polymorphism through an approach similar to type classes and implicits. Like type classes, a new kind of type is used to constrain parametric type variables. New concepts are defined using a concept construct. Classes with the required members of a concept automatically have an instance for that concept, and further instances can be defined using the concept_map construct. Like implicits, concepts cannot be inferred and are not canonical. Concepts allow overlapping instances, using C++’s complex overloading rules to resolve ambiguities. Concept maps can override the default instance for a type. These features can be useful, but make reasoning about implicit parameters more difficult. Our proposal requires all implicit modules to be explicit and always gives an ambiguity error if multiple matching implicit modules are available. F#’s static constraints [19] are similar to concepts without support for concept maps. 5 This should not be confused with more recent “concepts lite” proposal, due for inclusion in the next C++ standard Leo White, Frédéric Bour & Jeremy Yallop 61 7.5 Modular type classes Dreyer et al. [5] describe modular type classes, a type class system which uses ML module types as type classes and ML modules as type class instances. This system sticks closely to the design of Haskell type classes. In particular it infers type class constraints, and gives ambiguity errors at the point when modules are made implicit. In order to maintain coherence in the presence of inferred constraints and without canonicity, the system includes a number of undesirable restrictions: • Modules may only be made implicit at the top-level; they cannot be introduced within a module or a value definition. • Only module definitions are permitted at the top-level; all value definitions must be contained within a sub-module. • All top-level module definitions must have an explicit signature. These restrictions essentially split the language into an outer layer that consists only of module definitions and an inner layer within each module definition. Within the inner layer instances are canonical and constraints are inferred. In the outer layer instances are not canonical and all types must be given explicitly; there is no type inference. In order to give ambiguity errors at the point where modules are made implicit, one further restriction is required: all implicit modules must define a type named t and resolution is always done based on this type. By basing our design on implicits rather than type classes we avoid such restrictions. Our proposal also includes higher-rank implicit parameters, higher-kinded implicit parameters and resolution based on multiple types. These are not included in the design of modular type classes. Wehr et al. [21] give a comparison and translation between modules and type classes. This translation does not consider the implicit aspect of type classes, but does illustrate the relationship between type class features (e.g. associated types) and module features (e.g. abstract types). 8 Future work This paper gives only an informal description of the type system and resolution procedure. Giving a formal description is left as future work. The implementation of our proposal described in Section 6 is only a prototype. Further work is needed to bring this prototype up to production quality. The two aspects of our proposal related to completeness of type inference: 1. The interdependence of type inference and resolution 2. The restrictions on resolution to avoid non-termination are inevitably compromises between maximising inference and maximising predictability. How to strike the best balance between these two goals is an open question. More work is needed to evaluate how predictable users find the various possible approaches in practice. The syntax used for implicit functors is suggestive of an extension to our proposal: functors with implicit arguments. In our proposal, arguments to functors are only resolved implicitly during resolution for other implicit arguments. Supporting such resolution more generally would be an interesting direction to explore as it would introduce ad-hoc polymorphism into the module language. 62 Modular implicits Further work is also needed to answer more practical questions: How well do modular implicits scale to large code bases? How best to design libraries using implicits? How efficient is implicit resolution on real world code bases? Acknowledgements We thank Stephen Dolan and Anil Madhavapeddy for helpful discussions, Andrew Kennedy for bringing Canonical Structures to our attention, and Oleg Kiselyov and the anonymous reviewers for their insightful comments. References [1] Manuel M. T. Chakravarty, Gabriele Keller, Simon L. Peyton Jones & Simon Marlow (2005): Associated types with class. In Jens Palsberg & Martı́n Abadi, editors: Proceedings of the 32nd ACM SIGPLANSIGACT Symposium on Principles of Programming Languages, POPL 2005, Long Beach, California, USA, January 12-14, 2005, ACM, pp. 1–13, doi:10.1145/1040305.1040306. Available at http://dl.acm. org/citation.cfm?id=1040305. [2] Pierre Chambart & Grégoire Henry (2012): Experiments in Generic Programming. OCaml Users and Developers Workshop. [3] Dominique Devriese & Frank Piessens (2011): On the bright side of type classes: instance arguments in Agda. In Manuel M. T. Chakravarty, Zhenjiang Hu & Olivier Danvy, editors: Proceeding of the 16th ACM SIGPLAN international conference on Functional Programming, ICFP 2011, Tokyo, Japan, September 1921, 2011, ACM, pp. 143–155, doi:10.1145/2034773.2034796. [4] Atze Dijkstra, Gerrit van den Geest, Bastiaan Heeren & S. Doaitse Swierstra (2007): Modelling Scoped Instances with Constraint Handling Rules. [5] Derek Dreyer, Robert Harper, Manuel M. T. Chakravarty & Gabriele Keller (2007): Modular type classes. In Martin Hofmann & Matthias Felleisen, editors: Proceedings of the 34th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages, POPL 2007, Nice, France, January 17-19, 2007, ACM, pp. 63–70, doi:10.1145/1190216.1190229. Available at http://dl.acm.org/citation.cfm? id=1190216. [6] Jacques Garrigue & Leo White (2014): Type-level module aliases: independent and equal. ML Family Workshop. [7] Douglas Gregor, Jaakko Järvi, Jeremy G. Siek, Bjarne Stroustrup, Gabriel Dos Reis & Andrew Lumsdaine (2006): Concepts: linguistic support for generic programming in C++. In Peri L. Tarr & William R. Cook, editors: Proceedings of the 21th Annual ACM SIGPLAN Conference on Object-Oriented Programming, Systems, Languages, and Applications, OOPSLA 2006, October 22-26, 2006, Portland, Oregon, USA, ACM, pp. 291–310, doi:10.1145/1167473.1167499. [8] Mark P. Jones (1995): A System of Constructor Classes: Overloading and Implicit Higher-Order Polymorphism. J. Funct. Program. 5(1), pp. 1–35, doi:10.1017/S0956796800001210. [9] Simon Peyton Jones, editor (2002): Haskell 98 Language and Libraries: The Revised Report. http://haskell.org/. Available at http://haskell.org/definition/haskell98-report.pdf. [10] Simon Peyton Jones, Mark Jones & Erik Meijer (1997): Type classes: exploring the design space. In: Haskell workshop, 1997. [11] Stefan Kaes (1988): Parametric Overloading in Polymorphic Programming Languages. In Harald Ganzinger, editor: ESOP ’88, 2nd European Symposium on Programming, Nancy, France, March 21-24, 1988, Proceedings, Lecture Notes in Computer Science 300, Springer, pp. 131–144, doi:10.1007/3-540-19027-9_9. Leo White, Frédéric Bour & Jeremy Yallop 63 [12] Ralf Lämmel & Simon Peyton Jones (2003): Scrap Your Boilerplate: A Practical Design Pattern for Generic Programming. SIGPLAN Not. 38(3), pp. 26–37, doi:10.1145/640136.604179. [13] Xavier Leroy, Damien Doligez, Alain Frisch, Jacques Garrigue, Didier Rémy & Jérôme Vouillon (2014): The OCaml system release 4.02: Documentation and user’s manual. Interne, Inria. Available at https://hal. inria.fr/hal-00930213. [14] Assia Mahboubi & Enrico Tassi (2013): Canonical Structures for the Working Coq User. In Sandrine Blazy, Christine Paulin-Mohring & David Pichardie, editors: Interactive Theorem Proving, Lecture Notes in Computer Science 7998, Springer Berlin Heidelberg, pp. 19–34, doi:10.1007/978-3-642-39634-2_5. [15] The Rust programming language. http://www.rust-lang.org. [16] Bruno C. d. S. Oliveira, Adriaan Moors & Martin Odersky (2010): Type classes as objects and implicits. In William R. Cook, Siobhán Clarke & Martin C. Rinard, editors: Proceedings of the 25th Annual ACM SIGPLAN Conference on Object-Oriented Programming, Systems, Languages, and Applications, OOPSLA 2010, October 17-21, 2010, Reno/Tahoe, Nevada, USA, ACM, pp. 341–360, doi:10.1145/1869459. 1869489. [17] Bruno C. d. S. Oliveira, Tom Schrijvers, Wontae Choi, Wonchan Lee & Kwangkeun Yi (2012): The implicit calculus: a new foundation for generic programming. In Jan Vitek, Haibo Lin & Frank Tip, editors: ACM SIGPLAN Conference on Programming Language Design and Implementation, PLDI ’12, Beijing, China - June 11 - 16, 2012, ACM, pp. 35–44, doi:10.1145/2254064.2254070. Available at http://dl.acm. org/citation.cfm?id=2254064. [18] Matthieu Sozeau & Nicolas Oury (2008): First-Class Type Classes. In Otmane Aı̈t Mohamed, César A. Muñoz & Sofiène Tahar, editors: Theorem Proving in Higher Order Logics, 21st International Conference, TPHOLs 2008, Montreal, Canada, August 18-21, 2008. Proceedings, Lecture Notes in Computer Science 5170, Springer, pp. 278–293, doi:10.1007/978-3-540-71067-7_23. [19] Don Syme, Luke Hoban, Tao Liu, Dmitry Lomov, James Margetson, Brian McNamara, Joe Pamer, Penny Orwick, Daniel Quirk, Chris Smith et al. (2005): The F# 3.0 Language Specification. [20] Philip Wadler & Stephen Blott (1989): How to Make ad-hoc Polymorphism Less ad-hoc. In: Conference Record of the Sixteenth Annual ACM Symposium on Principles of Programming Languages, Austin, Texas, USA, January 11-13, 1989, ACM Press, pp. 60–76, doi:10.1145/75277.75283. Available at http://dl. acm.org/citation.cfm?id=75277. [21] Stefan Wehr & Manuel M. T. Chakravarty (2008): ML Modules and Haskell Type Classes: A Constructive Comparison. In G. Ramalingam, editor: Programming Languages and Systems, 6th Asian Symposium, APLAS 2008, Bangalore, India, December 9-11, 2008. Proceedings, Lecture Notes in Computer Science 5356, Springer, pp. 188–204, doi:10.1007/978-3-540-89330-1_14. [22] Jeremy Yallop & Leo White (2014): Lightweight Higher-Kinded Polymorphism. In Michael Codish & Eijiro Sumii, editors: Functional and Logic Programming - 12th International Symposium, FLOPS 2014, Kanazawa, Japan, June 4-6, 2014. Proceedings, Lecture Notes in Computer Science 8475, Springer, pp. 119–135, doi:10.1007/978-3-319-07151-0_8.
0
arXiv:1707.04402v2 [cs.MA] 27 Feb 2018 Lenient Multi-Agent Deep Reinforcement Learning Gregory Palmer Karl Tuyls University of Liverpool United Kingdom [email protected] DeepMind and University of Liverpool United Kingdom [email protected] Daan Bloembergen Rahul Savani Centrum Wiskunde & Informatica The Netherlands [email protected] University of Liverpool United Kingdom [email protected] ABSTRACT Much of the success of single agent deep reinforcement learning (DRL) in recent years can be attributed to the use of experience replay memories (ERM), which allow Deep Q-Networks (DQNs) to be trained efficiently through sampling stored state transitions. However, care is required when using ERMs for multi-agent deep reinforcement learning (MA-DRL), as stored transitions can become outdated because agents update their policies in parallel [11]. In this work we apply leniency [23] to MA-DRL. Lenient agents map state-action pairs to decaying temperature values that control the amount of leniency applied towards negative policy updates that are sampled from the ERM. This introduces optimism in the valuefunction update, and has been shown to facilitate cooperation in tabular fully-cooperative multi-agent reinforcement learning problems. We evaluate our Lenient-DQN (LDQN) empirically against the related Hysteretic-DQN (HDQN) algorithm [22] as well as a modified version we call scheduled-HDQN, that uses average reward learning near terminal states. Evaluations take place in extended variations of the Coordinated Multi-Agent Object Transportation Problem (CMOTP) [8] which include fully-cooperative sub-tasks and stochastic rewards. We find that LDQN agents are more likely to converge to the optimal policy in a stochastic reward CMOTP compared to standard and scheduled-HDQN agents. KEYWORDS Distributed problem solving; Multiagent learning; Deep learning 1 INTRODUCTION The field of deep reinforcement learning has seen a great number of successes in recent years. Deep reinforcement learning agents have been shown to master numerous complex problem domains, ranging from computer games [17, 21, 26, 33] to robotics tasks [10, 12]. Much of this success can be attributed to using convolutional neural network (ConvNet) architectures as function approximators, allowing reinforcement learning agents to be applied to domains with large or continuous state and action spaces. ConvNets are often trained to approximate policy and value functions through sampling Proc. of the 17th International Conference on Autonomous Agents and Multiagent Systems (AAMAS 2018), M. Dastani, G. Sukthankar, E. Andre, S. Koenig (eds.), July 2018, Stockholm, Sweden © 2018 International Foundation for Autonomous Agents and Multiagent Systems (www.ifaamas.org). All rights reserved. https://doi.org/doi past state transitions stored by the agent inside an experience replay memory (ERM). Recently the sub-field of multi-agent deep reinforcement learning (MA-DRL) has received an increased amount of attention. Multiagent reinforcement learning is known for being challenging even in environments with only two implicit learning agents, lacking the convergence guarantees present in most single-agent learning algorithms [5, 20]. One of the key challenges faced within multiagent reinforcement learning is the moving target problem: Given an environment with multiple agents whose rewards depend on each others’ actions, the difficulty of finding optimal policies for each agent is increased due to the policies of the agents being non stationary [7, 14, 31]. The use of an ERM amplifies this problem, as a large proportion of the state transitions stored can become deprecated [22]. Due to the moving target problem reinforcement learning algorithms that converge in a single agent setting often fail in fullycooperative multi-agent systems with independent learning agents that require implicit coordination strategies. Two well researched approaches used to help parallel reinforcement learning agents overcome the moving target problem in these domains include hysteretic Q-learning [19] and leniency [23]. Recently Omidshafiei et al. [22] successfully applied concepts from hysteretic Q-learning to MA-DRL (HDQN). However, we find that standard HDQNs struggle in fully cooperative domains that yield stochastic rewards. In the past lenient learners have been shown to outperform hysteretic agents for fully cooperative stochastic games within a tabular setting [35]. This raises the question whether leniency can be applied to domains with a high-dimensional state space. In this work we show how lenient learning can be extended to MA-DRL. Lenient learners store temperature values that are associated with state-action pairs. Each time a state-action pair is visited the respective temperature value is decayed, thereby decreasing the amount of leniency that the agent applies when performing a policy update for the state-action pair. The stored temperatures enable the agents to gradually transition from optimists to average reward learners for frequently encountered state-action pairs, allowing the agents to outperform optimistic and maximum based learners in environments with misleading stochastic rewards [35]. We extend this idea to MA-DRL by storing leniency values in the ERM, and demonstrate empirically that lenient MA-DRL agents that learn implicit coordination strategies in parallel are able to converge on the optimal joint policy in difficult coordination tasks with stochastic AAMAS’18, July 2018, Stockholm, Sweden rewards. We also demonstrate that the performance of Hysteretic Q-Networks (HDQNs) within stochastic reward environments can be improved with a scheduled approach. Our main contributions can be summarized as follows. 1) We introduce the Lenient Deep Q-Network (LDQN) algorithm which includes two extensions to leniency: a retroactive temperature decay schedule (TDS) that prevents premature temperature cooling, and a T (s)-Greedy exploration strategy, where the probability of the optimal action being selected is based on the average temperature of the current state. When combined, TDS and T (s)Greedy exploration encourage exploration until average rewards have been established for later transitions. 2) We show the benefits of using TDS over average temperature folding (ATF) [35]. 3) We provide an extensive analysis of the leniency-related hyperparameters of the LDQN. 4) We propose a scheduled-HDQN that applies less optimism towards state transitions near terminal states compared to earlier transitions within the episode. 5) We introduce two extensions to the Cooperative Multi-agent Object Transportation Problem (CMOTP) [8], including narrow passages that test the agents’ ability to master fully-cooperative sub-tasks, stochastic rewards and noisy observations. 6) We empirically evaluate our proposed LDQN and SHDQN against standard HDQNs using the extended versions of the CMOTP. We find that while HDQNs perform well in deterministic CMOTPs, they are significantly outperformed by SHDQNs in domains that yield a stochastic reward. Meanwhile LDQNs comprehensively outperform both approaches within the stochastic reward CMOTP. The paper proceeds as follows: first we discuss related work and the motivation for introducing leniency to MA-DRL. We then provide the reader with the necessary background regarding how leniency is used within a tabular setting, briefly introduce hysteretic Q-learning and discuss approaches for clustering states based on raw pixel values. We subsequently introduce our contributions, including the Lenient-DQN architecture, T (s)-Greedy exploration, Temperature Decay Schedules, Scheduled-HDQN and extensions to the CMOTP, before moving on to discuss the results of empirically evaluating the LDQN. Finally we summarize our findings, and discuss future directions for our research. 2 RELATED WORK A number of methods have been proposed to help deep reinforcement learning agents converge towards an optimal joint policy in cooperative multi-agent tasks. Gupta et al. [13] evaluated policy gradient, temporal difference error, and actor critic methods on cooperative control tasks that included discrete and continuous state and action spaces, using a decentralized parameter sharing approach with centralized learning. In contrast our current work focuses on decentralized-concurrent learning. A recent successful approach has been to decompose a team value function into agentwise value functions through the use of a value decomposition network architecture [27]. Others have attempted to help concurrent learners converge through identifying and deleting obsolete state transitions stored in the replay memory. For instance, Foerster et al. [11] used importance sampling as a means to identify outdated Gregory Palmer, Karl Tuyls, Daan Bloembergen, and Rahul Savani transitions while maintaining an action observation history of the other agents. Our current work does not require the agents to maintain an action observation history. Instead we focus on optimistic agents within environments that require implicit coordination. This decentralized approach to multi-agent systems offers a number of advantages including speed, scalability and robustness [20]. The motivation for using implicit coordination is that communication can be expensive in practical applications, and requires efficient protocols [2, 20, 29]. Hysteretic Q-learning is a form of optimistic learning with a strong empirical track record in fully-observable multi-agent reinforcement learning [3, 20, 37]. Originally introduced to prevent the overestimation of Q-Values in stochastic games, hysteretic learners use two learning rates: a learning rate α for updates that increase the value estimate (Q-value) for a state-action pair and a smaller learning rate β for updates that decrease the Q-value [19]. However, while experiments have shown that hysteretic learners perform well in deterministic environments, they tend to perform sub-optimally in games with stochastic rewards. Hysteretic learners’ struggles in these domains have been attributed to learning rate β’s interdependencies with the other agents’ exploration strategies [20]. Lenient learners present an alternative to the hysteretic approach, and have empirically been shown to converge towards superior policies in stochastic games with a small state space [35]. Similar to the hysteretic approach, lenient agents initially adopt an optimistic disposition, before gradually transforming into average reward learners [35]. Lenient methods have received criticism in the past for the time they require to converge [35], the difficulty involved in selecting the correct hyperparameters, the additional overhead required for storing the temperature values, and the fact that they were originally only proposed for matrix games [20]. However, given their success in tabular settings we here investigate whether leniency can be applied successfully to MA-DRL. 3 BACKGROUND Q-Learning. The algorithms implemented for this study are based upon Q-learning, a form of temporal difference reinforcement learning that is well suited for solving sequential decision making problems that yield stochastic and delayed rewards [4, 34]. The algorithm learns Q-values for state-action pairs which are estimates of the discounted sum of future rewards (the return) that can be obtained at time t through selecting action at in a state st , providing the optimal policy is selected in each state that follows. Since most interesting sequential decision problems have a large state-action space, Q-values are often approximated using function approximators such as tile coding [4] or neural networks [33]. The parameters θ of the function approximator can be learned from experience gathered by the agent while exploring their environment, choosing an action at in state st according to a policy π , and updating the Q-function by bootstrapping the immediate reward r t +1 received in state st +1 plus the expected future reward from the next state (as given by the Q-function):  Q θ t +1 = θ t + α Yt − Q(st , at ; θ t ) ∇θ t Q(st , at ; θ t ). (1) Q Here, Yt is the bootstrap target which sums the immediate reward r t +1 and the current estimate of the return obtainable from the Lenient Multi-Agent Deep Reinforcement Learning AAMAS’18, July 2018, Stockholm, Sweden next state st +1 assuming optimal behaviour (hence the max operator) and discounted by γ ∈ (0, 1], given in Eq. (2). The Q-value Q(st , at ; θ t ) moves towards this target by following the gradient ∇θ t Q(st , at ; θ t ); α ∈ (0, 1] is a scalar used to control the learning rate. Q Yt ≡ r t +1 + γ max Q(st +1 , a; θ t ). (2) a ∈A Deep Q-Networks (DQN). In deep reinforcement learning [21] a multi-layer neural network is used as a function approximator, mapping a set of n-dimensional state variables to a set of mdimensional Q-values f : Rn → Rm , where m represents the number of actions available to the agent. The network parameters θ can be trained using stochastic gradient descent, randomly sampling past transitions experienced by the agent that are stored within an experience replay memory (ERM) [18, 21]. Transitions are tuples (st , at , st +1 , r t +1 ) consisting of the original state st , the action at , the resulting state st +1 and the immediate reward r t +1 . The network is trained to minimize the time dependent loss function Li (θ i ), h i Li (θ i ) = Es,a∼p(·) (Yt − Q(s, a; θ t ))2 , (3) where p(s, a) represents a probability distribution of the transitions stored within the ERM, and Yt is the target: Yt ≡ r t +1 + γQ(st +1 , argmax Q(st +1 , a; θ t ); θ t′ ). a ∈A (4) Equation (4) is a form of double Q-learning [32] in which the target action is selected using weights θ , while the target value is computed using weights θ ′ from a target network. The target network is a more stable version of the current network, with the weights being copied from current to target network after every n transitions [33]. Double-DQNs have been shown to reduce overoptimistic value estimates [33]. This notion is interesting for our current work, since both leniency and hysteretic Q-learning attempt to induce sufficient optimism in the early learning phases to allow the learning agents to converge towards an optimal joint policy. Hysteretic Q-Learning. Hysteretic Q-learning [19] is an algorithm designed for decentralised learning in deterministic multiagent environments, and which has recently been applied to MADRL as well [22]. Two learning rates are used, α and β, with β < α. The smaller learning rate β is used whenever an update would reduce a Q-value. This results in an optimistic update function which puts more weight on positive experiences, which is shown to be beneficial in cooperative multi-agent settings. Given a spectrum with traditional Q-learning at one end and maximum-based learning, where negative experiences are completely ignored, at the other, then hysteretic Q-learning lies somewhere in between depending on the value chosen for β. Leniency. Lenient learning was originally introduced by Potter and De Jong [25] to help cooperative co-evolutionary algorithms converge towards an optimal policy, and has later been applied to multi-agent learning as well [24]. It was designed to prevent relative overgeneralization [36], which occurs when agents gravitate towards a robust but sub-optimal joint policy due to noise induced by the mutual influence of each agent’s exploration strategy on others’ learning updates. Leniency has been shown to increase the likelihood of convergence towards the globally optimal solution in stateless coordination games for reinforcement learning agents [6, 23, 24]. Lenient learners do so by effectively forgiving (ignoring) sub-optimal actions by teammates that lead to low rewards during the initial exploration phase [23, 24]. While initially adopting an optimistic disposition, the amount of leniency displayed is typically decayed each time a state-action pair is visited. As a result the agents become less lenient over time for frequently visited state-action pairs while remaining optimistic within unexplored areas. This transition to average reward learners helps lenient agents avoid sub-optimal joint policies in environments that yield stochastic rewards [35]. During training the frequency with which lenient reinforcement learning agents perform updates that result in lowering the Qvalue of a state action pair (s, a) is determined by leniency and temperature functions, l(st , at ) and Tt (st , at ) respectively [35]. The relation of the temperature function is one to one, with each stateaction pair being assigned a temperature value that is initially set to a defined maximum temperature value, before being decayed each time the pair is visited. The leniency function l(st , at ) = 1 − e −K ∗Tt (st ,at ) (5) uses a constant K as a leniency moderation factor to determine how the temperature value affects the drop-off in lenience. Following the update, Tt (st , at ) is decayed using a discount factor β ∈ [0, 1] such that Tt +1 (st , at ) = β Tt (st , at ). Given a TD-Error δ , where δ = Yt − Q(st , at ; θ t ), leniency is applied to a Q-value update as follows: ( Q(st , at ) + αδ if δ > 0 or x > l(st , at ). Q(st , at ) = (6) Q(st , at ) if δ ≤ 0 and x ≤ l(st , at ). The random variable x ∼ U (0, 1) is used to ensure that an update on a negative δ is executed with a probability 1 − l(st , at ). Temperature-based exploration. The temperature values maintained by lenient learners can also be used to influence the action selection policy. Recently Wei and Luke [35] introduced Lenient Multiagent Reinforcement Learning 2 (LMRL2), where the average temperature of the agent’s current state is used with the Boltzmann action selection strategy to determine the weight of each action. As a result agents are more likely to choose a greedy action within frequently visited states while remaining exploratory for less-frequented areas of the environment. However, Wei and Luke [35] note that the choice of temperature moderation factor for the Boltzmann selection method is a non-trivial task, as Boltzmann selection is known to struggle to distinguish between Q-Values that are close together [15, 35]. Average Temperature Folding (ATF). If the agents find themselves in the same initial state at the beginning of each episode, then after repeated interactions the temperature values for state-action pairs close to the initial state can decay rapidly as they are visited more frequently. However, it is crucial for the success of the lenient learners that the temperatures for these state-action pairs remains sufficiently high for the rewards to propagate back from later stages, and to prevent the agents from converging upon a sub-optimal policy [35]. One solution to this problem is to fold the average temperature for the n actions available to the agent in st +1 into the AAMAS’18, July 2018, Stockholm, Sweden temperature that is being decayed for (st , at ) [35]. The extent to Í which this average temperature T t (st +1 ) = 1/n ni=1 Tt (st +1 , ai ) is folded in is determined by a constant υ as follows: ( Tt (st , at ) if st +1 is terminal. Tt +1 (st , at ) = β (7) (1 − υ)Tt (st , at ) + υT t (st +1 ) otherwise. Clustering states using autoencoders. In environments with a high dimensional or continuous state space, a tabular approach for mapping each possible state-action pair to a temperature as discussed above is no longer feasible. Binning can be used to discretize low dimensional continuous state-spaces, however further considerations are required regarding mapping semantically similar states to a decaying temperature value when dealing with high dimensional domains, such as image observations. Recently, researchers studying the application of count based exploration to Deep RL have developed interesting solutions to this problem. For example, Tang et al. [30] used autoencoders to automatically cluster states in a meaningful way in challenging benchmark domains including Montezuma’s Revenge. The autoencoder, consisting of convolutional, dense, and transposed convolutional layers, can be trained using the states stored in the agent’s replay memory [30]. It then serves as a pre-processing function д : S → RD , with a dense layer consisting of D neurons with a saturating activation function (e.g. a Sigmoid function) at the centre. SimHash [9], a locality-sensitive hashing (LSH) function, can be applied to the rounded output of the dense layer to generate a hash-key ϕ for a state s. This hash-key is computed using a constant k × D matrix A with i.i.d. entries drawn from a standard Gaussian distribution N (0, 1) as  ϕ(s) = sдn A д(s) ∈ {−1, 1}k . (8) where д(s) is the autoencoder pre-processing function, and k controls the granularity such that higher values yield a more finegrained clustering [30]. 4 ALGORITHMIC CONTRIBUTIONS In the following we describe our main algorithmic contributions. First we detail our newly proposed Lenient Deep Q-Network, and thereafter we discuss our extension to Hysteretic DQN, which we call Scheduled HDQN. 4.1 Lenient Deep Q-Network (LDQN) Approach. Combining leniency with DQNs requires careful considerations regarding the use of the temperature values, in particular when to compute the amount of leniency that should be applied to a state transition that is sampled from the replay memory. In our initial trials we used leniency as a mechanism to determine which transitions should be allowed to enter the ERM. However, this approach led to poor results, presumably due to the agents developing a bias during the initial random exploration phase where transitions were stored indiscriminately. To prevent this bias we use an alternative approach where we compute and store the amount of leniency at time t within the ERM tuple: (st −1 , at −1 , r t , st , l(st , at )t ). The amount of leniency that is stored is determined by the current temperature value T associated with the hash-key ϕ(s) for state s Gregory Palmer, Karl Tuyls, Daan Bloembergen, and Rahul Savani and the selected action a, similar to Eq. (5): l(s, t) = 1 − e −k ×T (ϕ(s),a) . (9) We use a dictionary to map each (ϕ(s), a) pair encountered to a temperature value, where the hash-keys are computed using Tang et al.’s [30] approach described in Section 3. If a temperature value does not yet exist for (ϕ(s), a) within the dictionary then an entry is created, setting the temperature value equal to MaxT emperature. Otherwise the current temperature value is used and subsequently decayed, to ensure the agent will be less lenient when encountering a semantically similar state in the future. As in standard DQN the aim is to minimize the loss function of Eq. (3), with the modification that for each sample j chosen from the replay memory for which the leniency conditions of Eq. (6) are not met, are ignored. Retroactive Temperature Decay Schedule (TDS). During initial trials we found that temperatures decay rapidly for state-action pairs belonging to challenging sub-tasks in the environment, even when using ATF (Section 3). In order to prevent this premature cooling of temperatures we developed an alternative approach using a pre-computed temperature decay schedule β 0 , . . . , βn with a step limit n. The values for β are computed using an exponent ρ which is decayed using a decay rate d: βn = e ρ×d t (10) for each t, 0 ≤ t < n. Upon reaching a terminal state the temperature decay schedule is applied as outlined in Algorithm 1. The aim is to ensure that temperature values of state-action pairs encountered during the early phase of an episode are decayed at a slower rate than those close to the terminal state transition (line 4). We find that maintaining a slow-decaying maximum temperature ν (lines 5-7) that is decayed using a decay rate µ helps stabilize the learning process when ϵ-Greedy exploration is used. Without the decaying maximum temperature the disparity between the low temperatures in well explored areas and the high temperatures in relatively unexplored areas has a destabilizing effect during the later stages of the learning process. Furthermore, for agents also using the temperature values to guide their exploration strategy (see below), ν can help ensure that the agents transition from exploring to exploiting within reasonable time. The decaying maximum temperature ν is used whenever T (ϕ(st −1 ), at −1 ) > νt , or when agents fail at their task in environments where a clear distinction can be made between success and failure. Therefore TDS is best suited for domains that yield sparse large rewards. Applying the TDS after the agents fail at a task could result in the repeated decay of temperature values for state-action pairs leading up to a sub-task. For instance, the sub-task of transporting a heavy item of goods through a doorway may only require a couple of steps for trained agents who have learned to coordinate. However, untrained agents may require thousands of steps to complete the task. If a time-limit is imposed for the agents to deliver the goods, and the episode ends prematurely while an attempt is made to solve the sub-task, then the application of the TDS will result in the rapid decay of the temperature values associated with the frequently encountered state-action pairs. We resolve this problem by setting the temperature values Tt (ϕ(si ), ai ) > ν to ν at the end of incomplete Lenient Multi-Agent Deep Reinforcement Learning Algorithm 1 Application of temperature decay schedule (TDS) 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: Upon reaching a terminal state do n ← 0, steps ← steps taken during the episode for i = steps to 0 do if βnTt (ϕ(si ), ai ) < νt then Tt +1 (ϕ(si ), ai ) ← βnTt (ϕ(si ), ai ) else Tt +1 (ϕ(si ), ai ) ← νt end if n ←n+1 end for ν ← µν AAMAS’18, July 2018, Stockholm, Sweden 4.2 5 Figure 1: Lenient-DQN Architecture. We build on the standard Double-DQN architecture [33] by adding a lenient loss function (top right, see Section 4.1). Leniency values are stored in the replay memory along with the state transitions; we cluster semantically similar states using an autoencoder and SimHash (bottom left), and apply our retroactive temperature decay schedule (TDS, Algorithm 1). Actions are selected using the T (st )-Greedy exploration method. runs instead of repeatedly decaying them, thereby ensuring that the agents maintain a lenient disposition towards one another. T (st )-Greedy Exploration. During initial trials we encountered the same problems discussed by Wei and Luke [35] regarding the selection of the temperature moderation factor for the Boltzmann action selection strategy. This led to the development of a more intuitive T (st )-Greedy exploration method where the average temperature value T (st ) ∈ (0, 1] for a state st replaces the ϵ in the ϵ-Greedy action selection method. An exponent ξ is used to control the pace at which the agents transition from explorers to exploiters. The agent therefore selects action a = arдmax a Q(a) with a probability 1 − T (st )ξ and a random action with probability T (st )ξ . We outline our complete LDQN architecture in Figure 1. Scheduled-HDQN (SHDQ) Hysteretic Q-learners are known to converge towards sub-optimal joint policies in environments that yield stochastic rewards [35]. However, drawing parallels to lenient learning, where it is desirable to decay state-action pairs encountered at the beginning of an episode at a slower rate compared to those close to a terminal state, we consider that the same principle can be applied to Hysteretic Q-learning. Subsequently we implemented Scheduled-HDQN with a pre-computed learning rate schedule β 0 , . . . , βn where βn is set to a value approaching α, and for each βt , 0 ≤ t < n, we have βt = d n−t βn using a decay coefficient d ∈ (0, 1]. The state transitions encountered throughout each episode are initially stored within a queue data-structure. Upon reaching a terminal state the n statetransitions are transferred to the ERM as (st , st +1 , r t +1 , at , βt ) for t ∈ {0, . . . , n}. Our hypothesis is that storing β values that approach α for state-transitions leading to the terminal state will help agents converge towards optimal joint policies in environments that yield sparse stochastic rewards. EMPIRICAL EVALUATION CMOTP Extensions. We subjected our agents to a range of Coordinated Multi-Agent Object Transportation Problems (CMOTPs) inspired by the scenario discussed in Buşoniu et al. [8], in which two agents are tasked with delivering one item of goods to a dropzone within a grid-world. The agents must first exit a room one by one before locating and picking up the goods by standing in the grid cells on the left and right hand side. The task is fully cooperative, meaning the goods can only be transported upon both agents grasping the item and choosing to move in the same direction. Both agents receive a positive reward after placing the goods inside the drop-zone. The actions available to each agent are to either stay in place or move left, right, up or down. We subjected our agents to three variations of the CMOTP, depicted in Figure 2, where each A represents one of the agents, G the goods, and D-ZONE / DZ mark the drop-zone(s). The layout in sub-figure 2a is a larger version of the original layout [8], while the layout in sub-figure 2b introduces narrow-passages between the goods and the drop-zone, testing whether the agents can learn to coordinate in order to overcome challenging areas within the environment. The layout in sub-figure 2c tests the agents’ response to stochastic rewards. Drop-zone 1 (DZ1) yields a reward of 0.8, whereas dropzone 2 (DZ2) returns a reward of 1 on 60% of occasions and only 0.4 on the other 40%. DZ1 therefore returns a higher reward on average, 0.8 compared to the 0.76 returned by DZ2. A slippery surface can be added to introduce stochastic state transitions to the CMOTP, a common practice within grid-world domains where the agents move in an unintended direction with a predefined probability at each time-step. Setup. We conduct evaluations using a Double-DQN architecture [33] as basis for the algorithms. The Q-network consists of 2 convolutional layers with 32 and 64 kernels respectively, a fully connected layer with 1024 neurons and an output neuron for each action. The agents are fed a 16 × 16 tensor representing a grayscale version of the grid-world as input. We use the following pixel values to represent the entities in our grid-world: Aдent1 = 250, Aдent2 = 200, Goods = 150 and Obstacles = 50. Adam [16] is used AAMAS’18, July 2018, Stockholm, Sweden (a) Original (b) Narrow-Passage Gregory Palmer, Karl Tuyls, Daan Bloembergen, and Rahul Savani (c) Stochastic Figure 2: CMOTP Layouts to optimize the networks. Our initial experiments are conducted within a noise free environment, enabling us to speed up the testing of our LDQN algorithm without having to use an autoencoder for hashing; instead we apply python’s xxhash. We subsequently test the LDQN with the autoencoder for hashing in a noisy version of the stochastic reward CMOTP. The autoencoder consists of 2 convolutional Layers with 32 and 64 kernels respectively, 3 fully connected layers with 1024, 512, and 1024 neurons followed by 2 transposed convolutional layers. For our Scheduled-HDQN agents we pre-compute β 0 to n by setting βn = 0.9 and applying a decay coefficient of d = 0.99 at each step t = 1 to n, i.e. βn−t = 0.99t βn , with βn−t being bounded below at 0.4. We summarize the remaining hyper-parameters in Table 1. In Section 7 we include an extensive analysis of tuning the leniency related hyper-parameters. We note at this point that each algorithm used the same learning rate α specified in Table 1. Component Hyper-parameter Setting DQN-Optimization Learning rate α Discount rate γ Steps between target network synchronization ERM Size 0.0001 0.95 5000 250’000 ϵ -Greedy Exploration Initial ϵ value ϵ Decay factor Minimum ϵ Value 1.0 0.999 0.05 Leniency MaxTemperature Temperature Modification Coefficient K TDS Exponent ρ TDS Exponent Decay Rate d Initial Max Temperature Value ν Max Temperature Decay Coefficient µ 1.0 2.0 -0.01 0.95 1.0 0.999 Autoencoder HashKey Dimensions k Number of sigmoidal units in the dense layer D 64 512 Table 1: Hyper-parameters 6 identical actions per state transition. As a result thousands of state transitions are often required to deliver the goods and receive a reward while the agents explore the environment, preventing the use of a small replay memory where outdated transitions would be overwritten within reasonable time. As a result standard Double-DQN architectures struggled to master the CMOTP, failing to coordinate on a significant number of runs even when confronted with the relatively simple original CMOTP. We conducted 30 training runs of 5000 episodes per run for each LDQN and HDQN configuration. Lenient and hysteretic agents with β < 0.8 fared significantly better than the standard DoubleDQN, converging towards joint policies that were only a few steps shy of the optimal 33 steps required to solve the task. Lenient agents implemented with both ATF and TDS delivered a comparable performance to the hysteretic agents with regards to the average steps per episode and the coordinated steps percentage measured over the final 100 steps of each episode (Table 2, left). However, both LDQN-ATF and LDQN-TDS averaged a statistically significant higher number of steps per training run compared to hysteretic agents with β < 0.7. For the hysteretic agents we observe a statistically significant increase in the average steps per run as the values for β increase, while the average steps and coordinated steps percentage over the final 100 episodes remain comparable. Narrow Passage CMOTP. Lenient agents implemented with ATF struggle significantly within the narrow-passage CMOTP, as evident from the results listed in Table 2 (right). We find that the average temperature values cool off rapidly over the first 100 episodes within the Pickup and Middle compartments, as illustrated in Figure 3. Meanwhile agents using TDS manage to maintain sufficient leniency over the first 1000 episodes to allow rewards to propagate backwards from the terminal state. We conducted ATF experiments with a range of values for the fold-in constant υ (0.2, 0.4 and 0.8), but always witnessed the same outcome. Slowing down the temperature decay would help agents using ATF remain lenient for longer, with the side-effects of an overoptimistic disposition in stochastic environments, and an increase in the number of steps required for convergence if the temperatures are tied to the action selection policy. Using TDS meanwhile allows agents to maintain sufficient leniency around difficult sub-tasks within the environment while being able to decay later transitions at a faster rate. As a result agents using TDS can learn the average rewards for state transitions close to the terminal state while remaining optimistic for updates to earlier transitions. DETERMINISTIC CMOTP RESULTS Original CMOTP. The CMOTP represents a challenging fully cooperative task for parallel learners. Past research has shown that deep reinforcement learning agents can converge towards cooperative policies in domains where the agents receive feedback for their individual actions, such as when learning to play pong with the goal of keeping the ball in play for as long as possible [28]. However, in the CMOTP feedback is only received upon delivering the goods after a long series of coordinated actions. No immediate feedback is available upon miscoordination. When using uniform action selection the agents only have a 20% chance of choosing Figure 3: Average temperature per compartment Lenient Multi-Agent Deep Reinforcement Learning SPE CSP SPR Hyst. β = 0.5 36.4 92% 1’085’982 Hyst. β = 0.6 36.1 92% 1’148’652 Original CMOTP Results Hyst. β = 0.7 Hyst. β = 0.8 36.8 528.9 92% 91% 1’408’690 3’495’657 AAMAS’18, July 2018, Stockholm, Sweden LDQN ATF 36.9 92% 1’409’720 LDQN TDS 36.8 92% 1’364’029 Hyst. β = 0.5 45.25 92% 1’594’968 Narrow-Passage CMOTP Results Hyst. β = 0.6 LDQN ATF 704.9 376.2 89% 90% 4’736’936 3’950’670 LDQN TDS 45.7 92% 2’104’637 Table 2: Deterministic CMTOP Results, including average steps per episode (SPE) over the final 100 episodes, coordinated steps percentages (CSP) over the final 100 episodes, and the average steps per training run (SPR). The success of HDQN agents within the narrow-passage CMOTP depends on the value chosen for β. Agents with β > 0.5 struggle to coordinate, as we observed over a large range of β values, exemplars of which are given in Table 2. The only agents that converge upon a near optimal joint-policy are those using LDQN-TDS and HDQN (β = 0.5). We performed a Kolmogorov-Smirnov test with a null hypothesis that there is no significant difference between the performance metrics for agents using LDQN-TDS and HDQN (β = 0.5). We fail to reject the null hypothesis for average steps per episode and percentage of coordinated steps for the final 100 episodes. However, HDQN (β = 0.5) averaged significantly less steps per run while maintaining less overhead, replicating previous observations regarding the strengths of hysteretic agents within deterministic environments. 7 STOCHASTIC CMOTP RESULTS In the stochastic setting we are interested in the percentage of runs for each algorithm that converge upon the optimal joint policy, which is for the agents to deliver the goods to dropzone 1, yielding a reward of 0.8, as opposed to dropzone 2 which only returns an average reward of 0.76 (see Section 5). We conducted 40 runs of 5000 episodes for each algorithm. As discussed in Section 6, HDQN agents using β > 0.7 frequently fail to coordinate in the deterministic CMOTP. Therefore, setting β = 0.7 is the most likely candidate to succeed at solving the stochastic reward CMOTP for standard HDQN architectures. However, agents using HDQN (β = 0.7) only converged towards the optimal policy on 42.5% of runs. The scheduled-HDQN performed significantly better achieving a 77.5% optimal policy rate. Furthermore the SHDQN performs well when an additional funnel-like narrowpassage is inserted close to the dropzones, with 93% success rate. The drop in performance upon removing the funnel suggests that the agents are led astray by the optimism applied to earlier transitions within each episode, presumably around the pickup area where a crucial decision is made regarding the direction in which the goods should be transported. LDQN using ϵ−Greedy exploration performed similar to SHDQN, converging towards the optimal joint policy on 75% of runs. Meanwhile LDQNs using T (st )-Greedy exploration achieved the highest percentages of optimal joint-policies, with agents converging on 100% of runs for the following configuration: K = 3.0, d = 0.9, ξ = 0.25 and µ = 0.9995, which will be discussed in more detail below. However the percentage of successful runs is related to the choice of hyperparameters. We therefore include an analysis of three critical hyperparameters: • The temperature Modification Coefficient K, that determines the speed at which agents transition from optimist to average reward learner (sub-figure 4a). Values: 1, 2 and 3 • The TDS decay-rate d which controls the rate at which temperatures are decayed n-steps prior to the terminal state (sub-figure 4b). Values: 0.9, 0.95 and 0.99 • T (st )-Greedy exploration exponent ξ , controlling the agent’s transition from explorer to exploiter, with lower values for ξ encouraging exploration. Values: 0.25, 0.5 and 1.0 (a) Leniency Schedules (b) TDS Figure 4: TMC and TDS schedules used during analysis. We conducted 40 simulation runs for each combination of the three variables. To determine how well agents using LDQN can cope with stochastic state transitions we added a slippery surface where each action results in a random transition with 10% probability 1 . The highest performing agents used a steep temperature decay schedule that maintains high temperatures for early transitions (d = 0.9 or d = 0.95) with temperature modification coefficients that slow down the transition from optimist to average reward learner (K = 2 or k = 3), and exploration exponents that delay the transition from explorer to exploiter (ξ = 0.25 or ξ = 0.5). This is illustrated in the heat-maps in Figure 5. When using a TDS with a more gradual incline (d = 0.99) the temperature values from earlier state transitions decay at a similar rate to those near terminal states. In this setting choosing larger values for K increases the likelihood of the agents converging upon a sub-optimal policy prior to having established the average rewards available in later states, as evident from the results plotted in sub-figure 5c. Even when setting the exploration exponent ξ to 0.25 the agents prematurely transition to exploiter while holding an overoptimistic disposition towards follow-on states. Interestingly when K < 3 agents often converge towards the optimal joint-policy despite setting d = 0.99. However, the highest percentages of optimal runs (97.5%) were achieved through combining a steep TDS (d = 0.9 or d = 0.95) with the slow transition to average reward learner (k = 3) and exploiter (ξ = 0.25). Meanwhile the lowest percentages for all TDSs resulted from insufficient leniency (K = 1) and exploration (ξ = 1.0). Using one of the best-performing configuration (K = 3.0, d = 0.9 and ξ = 0.25) we conducted further trials analyzing the agents’ 1 Comparable results were obtained during preliminary trials without a slippery surface. AAMAS’18, July 2018, Stockholm, Sweden Gregory Palmer, Karl Tuyls, Daan Bloembergen, and Rahul Savani 8 (a) d = 0.9 (b) d = 0.95 (c) d = 0.99 Figure 5: Analysis of the LDQN hyperparameters. The heat-maps show the percentage of runs that converged to the optimal joint-policy (darker is better). sensitivity to the maximum temperature decay coefficient µ. We conducted an additional set of 40 runs where µ was increased from 0.999 to 0.9995. Combining T (S)-Greedy with the slow decaying µ = 0.9995 results in the agents spending more time exploring the environment at the cost of requiring longer to converge, resulting in an additional 1’674’106 steps on average per run. However, the agents delivered the best performance, converging towards the optimal policy on 100% runs conducted. Continuous State Space Analysis. Finally we show that semantically similar state-action pairs can be mapped to temperature values using SimHash in conjunction with an autoencoder. We conducted experiments in a noisy version of the stochastic CMTOP, where at each time step every pixel value is multiplied by a unique coefficient drawn from a Gaussian distribution X ∼ N (1.0, 0.01). A non-sparse tensor is used to represent the environment, with background cells set to 1.0 prior to noise being applied. Agents using LDQNs with xxhash converged towards the suboptimal joint policy after the addition of noise as illustrated in Figure 6, with the temperature values decaying uniformly in tune with ν . LDQN-TDS agents using an autoencoder meanwhile converged towards the optimal policy on 97.5% of runs. It is worth pointing out that the autoencoder introduces a new set of hyperparameters that require consideration, including the size D of the dense layer at the centre of the autoencoder and the dimensions K of the hash-key, raising questions regarding the influence of the granularity on the convergence. We leave this for future work. 9 Figure 6: Noisy Stochastic CMOTP Average Reward DISCUSSION & CONCLUSION Our work demonstrates that leniency can help MA-DRL agents solve a challenging fully cooperative CMOTP using high-dimensional and noisy images as observations. Having successfully merged leniency with a Double-DQN architecture raises the question regarding how well our LDQN will work with other state of the art components. We have recently conducted preliminary stochastic reward CMOTP trials with agents using LDQN with a Prioritized Experience Replay Memory [1]. Interestingly the agents consistently converged towards the sub-optimal joint policy. We plan to investigate this further in future work. In addition our research raises the question how well our extensions would perform in environments where agents receive stochastic rewards throughout the episode. To answer this question we plan to test our LDQN within a hunter prey scenario where each episode runs for a fixed number of time-steps, with the prey being re-inserted at a random position each time it is caught [20]. Furthermore we plan to investigate how our LDQN responds to environments with more than two agent by conducting CMOTP and hunter-prey scenarios with four agents. To summarize our contributions: 1) In this work we have shown that leniency can be applied to MA-DRL, enabling agents to converge upon optimal joint policies within fully-cooperative environments that require implicit coordination strategies and yield stochastic rewards. 2) We find that LDQNs significantly outperform standard and scheduled-HDQNs within environments that yield stochastic rewards, replicating findings from tabular settings [35]. 3) We introduced two extensions to leniency, including a retroactive temperature decay schedule that prevents the premature decay of temperatures for state-action pairs and a T (st )-Greedy exploration strategy that encourages agents to remain exploratory in states with a high average temperature value. The extensions can in theory also be used by lenient agents within non-deep settings. 4) Our LDQN hyperparameter analysis revealed that the highest performing agents within stochastic reward domains use a steep temperature decay schedule that maintains high temperatures for early transitions combined with a temperature modification coefficient that slows down the transition from optimist to average reward learner, and an exploration exponent that delays the transition from explorer to exploiter. 5) We demonstrate that the CMOTP [8] can be used as a benchmarking environment for MA-DRL, requiring reinforcement learning agents to learn fully-cooperative joint-policies from processing high dimensional and noisy image observations. 6) Finally, we introduce two extensions to the CMOTP. First we include narrow passages, allowing us to test lenient agents’ ability to prevent the premature decay of temperature values. Our second extension introduces two dropzones that yield stochastic rewards, testing the agents’ ability to converge towards an optimal joint-policy while receiving misleading rewards. ACKNOWLEDGMENTS We thank the HAL Allergy Group for partially funding the PhD of Gregory Palmer and gratefully acknowledge the support of NVIDIA Corporation with the donation of the Titan X Pascal GPU that enabled this research. Lenient Multi-Agent Deep Reinforcement Learning REFERENCES [1] Ioannis Antonoglou, John Quan Tom Schaul, and David Silver. 2015. Prioritized Experience Replay. arXiv preprint arXiv:1511.05952 (2015). [2] Tucker Balch and Ronald C Arkin. 1994. Communication in reactive multiagent robotic systems. Autonomous robots 1, 1 (1994), 27–52. [3] Nikos Barbalios and Panagiotis Tzionas. 2014. A robust approach for multi-agent natural resource allocation based on stochastic optimization algorithms. Applied Soft Computing 18 (2014), 12–24. [4] Andrew Barto and Richard Sutton. 1998. Reinforcement learning: An introduction. MIT press. [5] Daan Bloembergen, Daniel Hennes, Michael Kaisers, and Karl Tuyls. 2015. Evolutionary dynamics of multi-agent learning: A survey. Journal of Artificial Intelligence Research 53 (2015), 659–697. [6] Daan Bloembergen, Michael Kaisers, and Karl Tuyls. 2011. Empirical and theoretical support for lenient learning. In The 10th International Conference on Autonomous Agents and Multiagent Systems-Volume 3. International Foundation for Autonomous Agents and Multiagent Systems, 1105–1106. [7] Lucian Busoniu, Robert Babuska, and Bart De Schutter. 2008. A comprehensive survey of multiagent reinforcement learning. IEEE Transactions on Systems, Man, And Cybernetics-Part C: Applications and Reviews, 38 (2), 2008 (2008). [8] Lucian Buşoniu, Robert Babuška, and Bart De Schutter. 2010. Multi-agent reinforcement learning: An overview. In Innovations in multi-agent systems and applications-1. Springer, 183–221. [9] Moses S Charikar. 2002. Similarity estimation techniques from rounding algorithms. In Proceedings of the thiry-fourth annual ACM symposium on Theory of computing. ACM, 380–388. [10] Tim de Bruin, Jens Kober, Karl Tuyls, and Robert Babuška. 2015. The importance of experience replay database composition in deep reinforcement learning. In Deep Reinforcement Learning Workshop, NIPS. [11] Jakob Foerster, Nantas Nardelli, Gregory Farquhar, Philip Torr, Pushmeet Kohli, Shimon Whiteson, et al. 2017. Stabilising Experience Replay for Deep Multi-Agent Reinforcement Learning. arXiv preprint arXiv:1702.08887 (2017). [12] Shixiang Gu, Ethan Holly, Timothy Lillicrap, and Sergey Levine. 2016. Deep Reinforcement Learning for Robotic Manipulation with Asynchronous Off-Policy Updates. arXiv preprint arXiv:1610.00633 (2016). [13] Jayesh K Gupta, Maxim Egorov, and Mykel Kochenderfer. 2017. Cooperative Multi-Agent Control Using Deep Reinforcement Learning. In Proceedings of the Adaptive and Learning Agents workshop (at AAMAS 2017). [14] Pablo Hernandez-Leal, Michael Kaisers, Tim Baarslag, and Enrique Munoz de Cote. 2017. A Survey of Learning in Multiagent Environments: Dealing with Non-Stationarity. arXiv preprint arXiv:1707.09183 (2017). [15] Leslie Pack Kaelbling, Michael L Littman, and Andrew W Moore. 1996. Reinforcement learning: A survey. Journal of artificial intelligence research 4 (1996), 237–285. [16] Diederik P. Kingma and Jimmy Ba. 2014. Adam: A Method for Stochastic Optimization. In Proceedings of the 3rd International Conference on Learning Representations (ICLR). [17] Guillaume Lample and Devendra Singh Chaplot. 2017. Playing FPS Games with Deep Reinforcement Learning. AAAI (2017), 2140–2146. [18] Long-H Lin. 1992. Self-improving reactive agents based on reinforcement learning, planning and teaching. Machine learning 8, 3/4 (1992), 69–97. [19] Laëtitia Matignon, Guillaume J Laurent, and Nadine Le Fort-Piat. 2007. Hysteretic q-learning: an algorithm for decentralized reinforcement learning in cooperative multi-agent teams. In Intelligent Robots and Systems, 2007. IROS 2007. IEEE/RSJ International Conference on. IEEE, 64–69. [20] Laetitia Matignon, Guillaume J Laurent, and Nadine Le Fort-Piat. 2012. Independent reinforcement learners in cooperative Markov games: a survey regarding coordination problems. The Knowledge Engineering Review 27, 1 (2012), 1–31. [21] Volodymyr Mnih, Koray Kavukcuoglu, David Silver, Andrei A Rusu, Joel Veness, Marc G Bellemare, Alex Graves, Martin Riedmiller, Andreas K Fidjeland, Georg Ostrovski, et al. 2015. Human-level control through deep reinforcement learning. Nature 518, 7540 (2015), 529–533. [22] Shayegan Omidshafiei, Jason Pazis, Christopher Amato, Jonathan P How, and John Vian. 2017. Deep decentralized multi-task multi-agent reinforcement learning under partial observability. In International Conference on Machine Learning. 2681–2690. [23] Liviu Panait, Keith Sullivan, and Sean Luke. 2006. Lenient learners in cooperative multiagent systems. In Proceedings of the fifth international joint conference on Autonomous agents and multiagent systems. ACM, 801–803. [24] Liviu Panait, Karl Tuyls, and Sean Luke. 2008. Theoretical advantages of lenient learners: An evolutionary game theoretic perspective. Journal of Machine Learning Research 9, Mar (2008), 423–457. [25] Mitchell A Potter and Kenneth A De Jong. 1994. A cooperative coevolutionary approach to function optimization. In International Conference on Parallel Problem Solving from Nature. Springer, 249–257. [26] Tom Schaul, John Quan, Ioannis Antonoglou, and David Silver. 2015. Prioritized experience replay. arXiv preprint arXiv:1511.05952 (2015). AAMAS’18, July 2018, Stockholm, Sweden [27] Peter Sunehag, Guy Lever, Audrunas Gruslys, Wojciech Marian Czarnecki, Vinicius Zambaldi, Max Jaderberg, Marc Lanctot, Nicolas Sonnerat, Joel Z Leibo, Karl Tuyls, and Thore Graepel. 2017. Value-Decomposition Networks For Cooperative Multi-Agent Learning. arXiv preprint arXiv:1706.05296 (2017). [28] Ardi Tampuu, Tambet Matiisen, Dorian Kodelja, Ilya Kuzovkin, Kristjan Korjus, Juhan Aru, Jaan Aru, and Raul Vicente. 2017. Multiagent cooperation and competition with deep reinforcement learning. PLoS One 12, 4 (2017), e0172395. [29] Ming Tan. 1993. Multi-agent reinforcement learning: Independent vs. cooperative agents. In Proceedings of the tenth international conference on machine learning. 330–337. [30] Haoran Tang, Rein Houthooft, Davis Foote, Adam Stooke, Xi Chen, Yan Duan, John Schulman, Filip De Turck, and Pieter Abbeel. 2016. # Exploration: A Study of Count-Based Exploration for Deep Reinforcement Learning. arXiv preprint arXiv:1611.04717 (2016). [31] Karl Tuyls and Gerhard Weiss. 2012. Multiagent Learning: Basics, Challenges, and Prospects. AI Magazine 33, 3 (2012), 41–52. [32] Hado Van Hasselt. 2010. Double Q-learning. In Advances in Neural Information Processing Systems. 2613–2621. [33] Hado Van Hasselt, Arthur Guez, and David Silver. 2016. Deep Reinforcement Learning with Double Q-Learning. AAAI (2016), 2094–2100. [34] Christopher JCH Watkins and Peter Dayan. 1992. Q-learning. Machine learning 8, 3-4 (1992), 279–292. [35] Ermo Wei and Sean Luke. 2016. Lenient Learning in Independent-Learner Stochastic Cooperative Games. Journal of Machine Learning Research 17, 84 (2016), 1–42. http://jmlr.org/papers/v17/15-417.html [36] R Paul Wiegand. 2003. An analysis of cooperative coevolutionary algorithms. Ph.D. Dissertation. George Mason University Virginia. [37] Yinliang Xu, Wei Zhang, Wenxin Liu, and Frank Ferrese. 2012. Multiagent-based reinforcement learning for optimal reactive power dispatch. IEEE Transactions on Systems, Man, and Cybernetics, Part C (Applications and Reviews) 42, 6 (2012), 1742–1751.
1
"arXiv:1709.04176v1 [cs.GT] 13 Sep 2017 Computing the Shapley Value in Allocation Problems: Approxi(...TRUNCATED)
1
"Detecting Qualia in Natural and Artificial Agents Roman V. Yampolskiy Computer Engineering and Comp(...TRUNCATED)
1
"1 Denoising Autoencoders for Overgeneralization in Neural Networks Abstract—Despite the recent (...TRUNCATED)
1
"Expectation Learning for Adaptive Crossmodal Stimuli Association Pablo Barros1 , German I. Parisi1 (...TRUNCATED)
1
"arXiv:1711.10413v1 [cs.PL] 28 Nov 2017 Implementing implicit OpenMP data sharing on GPUs Gheorghe-(...TRUNCATED)
0
"Declarative Statistical Modeling with Datalog Vince Barany LogicBlox, Inc. Balder ten Cate LogicBl(...TRUNCATED)
0
"Visualizations for an Explainable Planning Agent Tathagata Chakraborti1 and Kshitij P. Fadnis2 and (...TRUNCATED)
1

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
10
Add dataset card