Year: 2021

Abstract:
The Transformer (Vaswani et al., 2017) has enjoyed remarkable success at learning representations for discrete-time sequences, such as natural language sentences. Yet there exists little work on generalizing its success to sequences of discrete events in continuous time. We design a generative point process model for this case based on a continuous-time Transformer. An actual or possible event at time t is embedded using attention over actual events at times < t. More generally, we propose a new way to compute fact embeddings and event probabilities for neural Datalog through time (Mei et al., 2020a), a neural-symbolic framework for event sequence modeling that automatically derives deep recurrent neural models from temporal logic programs. Our Transformers replace the LSTM-style mechanism to capture temporal dependencies. We evaluated our novel architecture on several synthetic and real-world datasets, evaluated by likelihood and prediction accuracy. On most of them, it surpasses the previous version and other strong competitors; on the others, it is comparable to the state-of-the-art.

heading: 1 INTRODUCTION
text: Event sequences are ubiquitous in real-world applications, such as healthcare, finance, education, commerce, gaming, audio, news, security, and social media. We propose an elegant way to embed events into a vector space RD. An actual or possible event at time t ∈ R is contextually embedded using attention over actual events at other times, in a way that considers their timing. Good event embeddings could be used in a variety of downstream tasks, similar to word token embeddings in BERT. In particular, we consider the task of predicting the next event (generative modeling): at each time t ∈ R, all of the possible events are embedded using masked attention over the preceding actual events, and those embeddings yield the instantaneous probabilities at time t of the possible events.
Our approach is a continuous-time generalization of the Transformer (Vaswani et al., 2017). Transformers scale up well to very large datasets and have achieved astonishing success at generative modeling of discrete-time sequences, such as natural-language documents (Radford et al., 2019; Brown et al., 2020) and proteins (Rao et al., 2021). We show in this paper that they are also effective for irregularly spaced continuous-time sequences, even in lower-data regimes.
We further show how to derive models from arbitrary NDTT programs. NDTT, or neural Datalog through time (Mei et al., 2020a), is a neural-symbolic framework for modeling event sequences. An NDTT program specifies logical rules that derive facts within a deductive database. Moreover, the facts in the database are embedded using a deep recurrent neural architecture that is automatically determined by the facts’ provenance. Among the derived facts at time t are the possible events at time t.
As a simple NDTT example, if u is a user and d is a document and u has appropriate permissions, then u may open d. The embedding and instantaneous probability of this possible event at time t depend on the embeddings at time t of u and d (or more precisely, of the facts that u is a user and d is a document). If the event actually occurs, it may change what facts are true at times > t and how their embeddings evolve over times > t. For instance, the NDTT program can state that if u opens d, this makes editing events possible, and also affects the future embeddings of u and d. These updated embeddings feed forward to help predict future events involving u and/or d. (They could also be exploited for other downstream predictive tasks, via multitask training or pretraining.) All of these effects are controlled by the hand-crafted rules and learned parameters of the NDTT program,
event’s embedding at layer ` depends ( ) on all preceding events at layer ` − 1. (The dashed arrows reflect residual connections as well as the fact that each event or fact also attends to itself.) Section 4 explains that the ee ff influences can be prevented by dropping the rule ff <- ee. Figure (b) shows an A-NDTT model from section 5, in which the company forum’s embedding at layer ` depends ( ) on all preceding events at layer `− 1 (via <- rules). The events or possible events at layer ` do not depend directly on preceding events; instead, their embeddings at time t are derived ( ) from the forum’s embedding at time t (via :- rules).
which are analogous to the hand-crafted structure and learned parameters of a graphical model, in that they enforce domain-appropriate conditional independence and parameter sharing.
We modify the NDTT architectures to use attention. In our architecture, a fact that can be derived in multiple ways, by different NDTT rules, uses multiple attention heads to examine the past. Du et al. (2016); Mei & Eisner (2017); Mei et al. (2020a) instead summarize the past using recurrent neural networks (RNNs). Our attentive approach has three advantages over theirs:
¬ A Transformer does not summarize the past. Our predictions at time t can examine an unboundedly large representation of the past (Rd embeddings of every event before t), not merely a fixeddimensional summary that was computed greedily from left to right (an RNN’s state at time t).
 A Transformer’s computation graph is broader and shallower. The breadth makes it easier to learn long-distance influences. The shallowness does make it impossible to represent inherently deep concepts such as parity, but it enables greater parallelism: the layer-` embeddings can be computed in parallel during training, as they depend only on layer `− 1 and not on one another.
® Our architecture is simpler and arguably more natural, while remaining competitive in our experiments. To describe how embeddings vary continuously during the period (ti, ti+1] between two events, Mei & Eisner (2017) had to stipulate an arbitrary family of parametric decay functions on t, and Mei et al. (2020a) had to design a complex method for pooling the parameters of these decay functions across multiple NDTT rules. In contrast, our embeddings are constructed “from scratch” at each time t simply by attending to the set of previous events, using t-specific query vectors that include a continuous positional embedding of t. As t ranges over (ti, ti+1], the attention weights over the first i events vary continuously with t, so the embeddings do so too.

heading: 2 CONTINUOUS-TIME TRANSFORMER FOR EMBEDDING EVENTS
text: Suppose we observe I events over a fixed time interval [0, T ). Each event is denoted mnemonically as e@t (i.e., “type e at time t”), where e ∈ {1, 2, . . . , E} is the event’s type. The observed event sequence is e1@t1, e2@t2, . . . , eI@tI , where 0 < t1 < t2 < . . . < tI < T .
For any observed or possible event e@t, we can compute an embedding JeK(t) ∈ RD by attending to a set H(e@t) of relevant events. (For the moment, imagine that H(e@t) consists of all the observed events ei@ti.) More precisely, JeK(t) is the concatenation of layer-wise embeddings
JeK(0)(t), JeK(1)(t), . . . , JeK(L)(t). For ` > 0, the layer-` embedding of e@t is computed as
JeK(`)(t) def= JeK(`−1)(t)︸ ︷︷ ︸ residual connection + tanh  ∑ f@s∈H(e@t) v(`)(f@s) α(`)(f@s, e@t)∑ f@s∈H(e@t) α (`)(f@s, e@t)  (1) where the unnormalized attention weight on each relevant event f@s ∈ H(k@t) is
α(`)(f@s, e@t) def = exp ( 1√ D k(`)(f@s) > q(`)(e@t) ) ∈ R (2)
In layer `, v(`), k(`), and q(`) are known as the value, key, and query vectors and are extracted from the layer-(`-1) event embeddings using learned layer-specific matrices V(`),K(`),Q(`):
v(`)(e@t) def = V(`) [ 1; JtK; JeK(`−1)(t) ] (3a)
k(`)(e@t) def = K(`) [ 1; JtK; JeK(`−1)(t) ] (3b)
q(`)(e@t) def = Q(`) [ 1; JtK; JeK(`−1)(t) ] (3c)
As the base case, JeK(0)(t) def= JeK(0) is a learned embedding of the event type e. JtK denotes an embedding of the time t; as proposed by Zuo et al. (2020), we use the same sinusoidal embedding as in Vaswani et al. (2017), but with t now being real instead of integer:
JtKd = cos(t/10000 d−1 D ) if d is odd and JtKd = sin(t/10000 d D ) if d is even (4)
We concatenate JtK to the rest of the embedding rather than adding it (cf. Kitaev & Klein, 2018; He et al., 2020); furthermore we do so again at every layer.
According to equations (1)–(3), to compute the layer-` embedding of an event, we only need the layer(`−1) embeddings of the relevant events. This makes it possible to compute the layer-` embeddings of all events in parallel.
The set of relevant events H(e@t) may be defined in a task-specific way. For example, to pretrain BERT-like embeddings (Devlin et al., 2018), we might use a corrupted version of {e1@t1, . . . , eI@tI} in which some ei@ti have been removed or replaced with mask@ti. Such embeddings could be pretrained with a BERT-like objective and then fine-tuned to predict properties of the observed events.

heading: 3 GENERATIVE MODELING OF CONTINUOUS-TIME EVENT SEQUENCES
text: In this paper, we focus on the task of predicting future events given past ones. At any time t, we would like to know what will happen at that time, given the actual events that happened before t. Our generative model is analogous to a Transformer language model (Radford et al., 2019; Brown et al., 2020), which, at each time t ∈ N, defines a probability distribution over the words in the vocabulary. In our setting, however, t ∈ R. With probability 1, nothing happens at time t. Each possible event e in our vocabulary has only an infinitesimal probability of occurring at time t. We write this probability as λe(t)dt where λe(t) ∈ R is called the (Poisson) intensity of type-e events at time t. More formally, the probability of such an event occurring during [t, t+ ) approaches λe(t) as →+ 0. We model λe(t) as a function of the top-layer embedding of the possible event e@t:
λe(t) def = softplus(w>e [1; JeKL(t)], τe) where softplus(x, τ) = τ log(1 + exp(x/τ)) > 0 (5) with learnable parameters we and τe > 0. We do this separately for each possible e@t, computing the embedding JeKL(t) using equations (1)–(3). To ensure that our model is generative, we compute JeKL(t) from only the previous events. Thus, we takeH(e@t) in equation (1) to consist of all the previously generated events ei@ti for ti < t, as well as the possible event e@t itself. Including e@t allows e@t itself to draw most of the attention if none of the previous events are very relevant (e.g., they are too far in the past), or all of the attention in the special case where no previous events exist (i.e., it ensures thatH(e@t) 6= ∅, preventing division by 0 in equation 1).
Embedding each possible e@t separately is somewhat expensive. The attention weights α(1), . . . , α(L) used to compute its embedding and intensity must be recomputed for each e and t. This is more
expressive but also more expensive than a standard Transformer language model, which instead models the probability of word e at time t as proportional to exp(w>e [1; JfKL(s)]) where JfKL(s) is the top-layer embedding of the previous word f@s, where t = s + 1, and can be reused for all possible choices of e@t. Why do we not follow that cheaper approach, using the previous event f@s in place of e@t in equation (5)? Because then λe(t) would depend only on s and not on t (a language model can rely on t = s+ 1, but we may have to evaluate intensities at all real-valued t ≥ s since our events are irregularly spaced). Our more expressive design also allows the attention vector used to compute λe(t) to depend on e, to support the “selective attention” of section 4 below.
As a speedup, however, we can associate each event type e with a coarse event type ē that has the same selective attention pattern, and replace JeKL(t) with JēKL(t) in equation (5). (However, equation (5) still uses the fine-grained we.) Now to compute λe(t), we only have to embed ē@t, which is a speedup if many of the possible event types e are associated with the same ē. In the case where we do not use selective attention, we can get away with using only a single coarse event type for the whole model—saving a runtime factor of E as in the cheaper approach. Note that the historyH still uses fine-grained embeddings, so if e@t actually occurs, we must then compute JeK0(t), . . . , JeKL(t). Our model falls into the family of multivariate point processes. Its log-likelihood is given by
I∑ i=1 log λei(ti)− ∫ T t=0 E∑ e=1 λe(t)dt (6)
This formula has been derived and discussed in previous work (Hawkes, 1971; Liniger, 2009; Mei & Eisner, 2017). Intuitively, during parameter training, each log λei(ti) is increased to explain why the observed event ei happened at time ti, while ∫ T t=0 ∑E e=1 λe(t)dt is decreased to explain why no event of any possible type k ever happened at other times. That is why we need to embed possible events and compute their intensities.

heading: 4 MULTI-HEAD SELECTIVE ATTENTION
text: We now enrich the formalism to allow selective attention. As in a graphical model, not all events should be able to influence one another. Consider a scenario with two event types: e means that Eve emails Adam, while f means that Frank emails Eve. As Frank does not know when Eve emailed Adam, past events of type e cannot influence his behavior. Therefore,H(f@t) should include past events of type f but not e, so that the embedding of f@t and hence the intensity function λf(t) pay zero attention to e events. In contrast, H(e@t) should still include past events of both types, since both are visible to Eve and can influence her behavior. We describe this situation with the edges f <- f, e <- e, e <- f. These edges are called rules, for reasons that will become clear in section 5.
Furthermore, when Eve decides whether to email Adam (e@t), we may reasonably suppose that she separately considers the embeddings of the past e events (e.g., “when was my last relevant email to Adam?”) versus the past f events (e.g., “what have I heard from Frank?”). For this reason, we associate different attention heads with the two rules that affect e, namely e <- e and e <- f. These heads may have different parameters, so that they seek out and obtain different information from the past via different queries, keys, and values. In general, we replace equation (1) with
JeK(`)(t) def= JeK(`−1)(t) + tanh (∑
r
e (`)
r (t)
) (7)
e (`) r (t) def = ∑ f@s∈Hr(e@t)
v (`) r (f@s) α (`) r (f@s, e@t)∑
f@s∈Hr(e@t) α (`) r (f@s, e@t)
(8)
where r in the summation ranges over rules e <- · · · . The historyHr(e@t) contains only those past events f@s that rule r makes visible to e, as well as e@t itself as discussed in section 3. The r-specific α and v quantities are defined using versions of equations (2)–(3) with r-specific parameters.1

heading: 5 ATTENTIVE NEURAL DATALOG THROUGH TIME
text: 1The NDTT formalism does allow parameters to be explicitly shared across rules when desired. Its :: notation (Mei et al., 2020a, Appendix B) can also be used in our setup.
Edges such as e <- f can be regarded as simple examples of rules in a Neural Datalog Through Time program (Mei et al., 2020a). We briefly review this formalism and then extend our approach from section 4 to handle all NDTT programs.
Datalog. Recall that Datalog (Ceri et al., 1989) is a traditional formalism for deductive databases. A deductive database holds both extensional facts, which are placed there by some external process, and intensional facts, which are transitively deduced from the extensional facts. A Datalog program is simply a set of rules that govern these deductions:
• h :- g1, ..., gn says to deduce h at any time t when g1, . . . , gn are all true (in the database).
A single rule can license many deductions. That is because the facts can have structured names, and h, g1, . . . gn can be patterns that match against those names. In the example at the bottom of page 1, we would have a rule like open(U,D) :- user(U), group(G), document(D), member(U,G), readable(D,G), where U, G, and D are variables. In English, this says that the event open(U,D) is possible2 if user U is a member of some group G such that document D is readable by G.
Datalog Through Time. Whenever extensional facts are added or removed, the intensional facts are instantly recomputed according to the deductive rules. Datalog Through Time is an extension in which extensional facts are automatically added and removed when the database is notified of the occurrence of events. This behavior is governed by two additional rule types:
• h <- f, g1, ..., gn says to add h at any time s when event f occurs and the gi are all true. • !h <- f, g1, ..., gn says to remove h at any time s satisfying the same conditions.
Thus, the proposition h is true at time t (i.e., appears as a fact in the database at time t) iff either ¶ h is deduced at time t, or · h was added at some time s < t and never removed at any time in (s, t).
Neural Datalog Through Time. It would be difficult to train a neural architecture to encode thousands or millions of structured boolean facts about the world in its state and to modify those encoded facts systematically and transitively in response to events. As a neuro-symbolic method, NDTT delegates that task to a symbolic database governed by manually specified Datalog Through Time rules. However, it augments the database by neurally embedding every fact in a vector space. Thus, iff a proposition h appears as a fact in the NDTT database at time t, it will be associated not only with the simple truth value true but also with an embedding JhK(t). This embedding is a learned representation of that fact at that time, and can be trained to be useful in downstream tasks. It captures details of when and how that fact was established (the fact’s provenance), since it is computed using learned parameters associated with the rules that deduced and/or added it.
For example, if we write NDTT rules user(U) <- · · · that add user(U) (perhaps redundantly) each time a relevant event affects it, then Juser(456)K(t) reflects the embeddings and timings of all events before t that affected user(456). This embedding may help predict what user 456 will do in future. In our example, if open(456,78) is deduced with the help of user(456), then the embedding Jopen(456,78)K(t)—and its probability—in turn depends on Juser(456)K(t) and varies along with it as t changes.
In general, if e denotes the time-varying boolean proposition that an event of type e is possible, it follows that JeK(t) will be defined at all times t when that proposition is true—i.e., at all times when e is possible. This embedding is used in equation (5) to model the intensity function λe(t), which governs when e is likely to actually occur.
Contribution. Our goal is to provide new formulas for the embeddings JhK(t), based on Transformerstyle attention rather than LSTM-style recurrence. We call this attentive NDTT, or A-NDTT. The potential advantages for accuracy, efficiency, and simplicity were explained in section 1.
Under A-NDTT, the layer-` embedding of h@t is then JhK(`)(t) def= JhK(`−1)(t) + tanh ( [h](`)(t) +
∑ r h (`) r (t)
) (9)
which is an augmented version of equation (7). Suppose h is true at time t because it was added by rule r (i.e., condition ·). Then the summand h (`)r (t) exists and is computed much as in equation (8), now
2Following Mei et al. (2020a), we use orange to indicate facts like openopen(U,D) that specify possible events.
with attention over all add times s. In other words,Hr(h@t) includes just those past events f@s such that f added h via r at some time s < t and h was never removed at any time in (s, t). It also includes h@t itself, as before. We make one enhancement: when the rule h <- f, g1, ..., gn causes h@t to attend to the specific past event f@s, we actually want attention to consider the embedding at time s of the entire add condition f, g1, . . . , gn. Thus the attention key of f@s for this purpose is now defined as k(`)(f@s) def= K(`)r [ 1; JsK; JfK(`−1)(s); Jg1K(`−1)(s); . . . JgnK(`−1)(s) ] (compare equation (3b)). Its attention value v(`)(f@s) is defined analogously, using a different matrix V(`)r .
How about the vector [h](`)(t) in equation (9)? For each rule that deduces h at time t (i.e., condition ¶), say h :- g1, . . . gn, we compute a nonlinear transform of the concatenated embeddings JgiK(`)(t). The resulting vectors are pooled to obtain [h](`)(t). (If there are no such rules, then [h](`)(t) = 0.) Here we follow exactly the recipe of Mei et al. (2020a), except that we now do it anew at each level `.
The specification of parameter dimensionalities is discussed in Appendix A0.
Mei et al. (2020a) give many examples of NDTT programs. Here is a simple example to illustrate the use of :- rules. Possible events are shown in orange and other possible facts in blue. e means that Eve posts a message to the company forum, while f means that Frank does so. Once the forum is created by a create event, its existence is a fact (called forum) whose embedding (called JforumK) always reflects all messages posted so far to the forum. Until the forum is destroyed, Eve and Frank can post to it, and the embedding and intensity of such messages depends on the current state of the forum:
1 forum <- createcreate. 2 forum <- ee. 3 forum <- ff.
4 ee :- forum. 5 ff :- forum. 6 !forum <- destroydestroy.
The resulting neural architecture is drawn in Figure 1b. If the company grows from 2 to K employees, then the program needs O(K) rules and hence O(K) parameters, which define how each employee’s messages affect the forum and vice-versa. Without the :- rules, we would have to list out O(K2) rules such as e <- f and hence would need O(K2) parameters, which define how each employee’s messages affect every other employee’s messages directly; this case is drawn in Figure 1a.
Actually, if the company has many employees E and a forum for each team T, NDTT rules can use capitalized variables to define the whole system concisely, using only O(1) rules and O(1) parameters.3 Here the possible facts and events have structured names like message(eve,sales), which would be an event in which employee eve posts a message to the sales team’s forum.
7 forum(T) <- createcreate(T). 8 forum(T) <- messagemessage(E,T).
9 messagemessage(E,T) :- forum(T), member(E,T). 10 !forum(T) <- destroydestroy(T).
Additional rules could describe how the member facts and their embeddings change over time, which may in turn affect the embeddings and predictions of future messages. See the discussion in section 1.

heading: 6 TRAINING AND INFERENCE
text: We can estimate the parameters by locally maximizing the log-likelihood given in equation (6) using any stochastic gradient method. Details are given in Appendix A, including Monte Carlo approximations to the integral. Given the learned parameters, we may wish to make a minimum Bayes risk prediction about the next event given the past history. A recipe can be found in Appendix B.

heading: 7 RELATED WORK
text: Multivariate point processes have been widely used in real-world applications, including document stream modeling (He et al., 2015; Du et al., 2015a), learning Granger causality (Xu et al., 2016; Zhang et al., 2020b), network analysis (Choi et al., 2015; Etesami et al., 2016), recommendation systems (Du et al., 2015b), and social network analysis (Guo et al., 2015; Lukasik et al., 2016).
Over the recent years, various neural models have been proposed to expand the expressiveness of point processes. They mostly use recurrent neural networks, or LSTMs (Hochreiter & Schmidhuber, 1997): in particular Du et al. (2016); Mei & Eisner (2017); Xiao et al. (2017a;b); Omi et al. (2019); Shchur et al. (2020); Mei et al. (2020a); Boyd et al. (2020). Models of this kind enjoy continuous and
3Although a notation is available to demand employee-specific and forum-specific parameters if desired.
infinite state spaces, as well as flexible transition functions, thus achieving superior performance on many real-world datasets, compared to classical models such as the Hawkes process (Hawkes, 1971).
The Transformer Hawkes process (Zuo et al., 2020) and self-attentive Hawkes process (Zhang et al., 2020a) are pioneering work in using generative Transformers (Vaswani et al., 2017; Radford et al., 2019; Brown et al., 2020) in point processes. The Transformer architecture allows their models to enjoy unboundedly large representations of histories, as well as great parallelism during training (see ¬ and  in section 1). But they only embed actual events with attention; the intensities of possible events rely on a simple linear extrapolation of the embedding of the most recent actual event.4 Our model embeds all possible events at all possible times with attention as well (see ® in section 1), thus being more flexible (see section 3) and achieving better performance (see section 8).

heading: 8 EXPERIMENTS
text: On several synthetic and real-world datasets, we evaluate our model’s held-out log-likelihood, and its success at predicting the time and type of the next event. We compare with multiple strong competitors. Experimental details are given in Appendix C.
We implemented our A-NDTT framework using PyTorch (Paszke et al., 2017) and pyDatalog (Carbonell et al., 2016), borrowing substantially from the public implementation of NDTT (Mei et al., 2020a). We then used it to implement our individual models. Our code and datasets are available at code-public-after-paper-published.

heading: 8.1 COMPARISON OF DIFFERENT TRANSFORMER ARCHITECTURES
text: We first verify the comparative advantages of our continuous-time Transformer over the following state-of-the-art neural event models. They are
Neural Hawkes process (NHP) (Mei & Eisner, 2017). At any time t, NHP uses a continuous-time LSTM to summarize the previous events into a multi-dimensional state vector, and conditions the intensities of all event types on that state.
Transformer Hawkes process (THP) (Zuo et al., 2020). THP directly applies the discrete-time generative Transformer, as discussed in section 7 and footnote 4.
Self-Attentive Hawkes Process (SAHP (Zhang et al., 2020a). SAHP is very similar to THP but uses a slightly more flexible intensity function; see footnote 4.
For the above models, we make use of their published implementation.5 Details are in Appendix C.2.
Attentive neural Hawkes process (A-NHP) This is our unstructured generative model from section 3. Since this model does not use selective attention, we speed up the intensity computations by defining them in terms of a single coarse event type, as described beneath equation (5). Thus, each event intensity λe(t) is computed by attention over all previous events, where the attention weights are independent of e. This parameter-sharing mechanism resembles the NHP, except that we now use a Transformer in place of an LSTM.6
In a pilot experiment, we draw sequences from randomly initialized models (details in Appendix C.1.1), and fit the above models on these synthetic datasets.The results are shown in Figure 2. As shown in Figure 2c, on the synthetic NHP data, the performance of A-NHP is essentially the same as that of NHP, meaning that A-NHP is still a good choice even when it is misspecified. This result is reassuring because A-NHP has less capacity in some ways (the circuit depth of a Transformer is fixed, whereas the circuit depth of an LSTM grows with the length of the sequence) and excess capacity in other ways (the Transformer has unbounded memory whereas the LSTM has finite-dimensional memory). We also tried fitting A-NHP to the synthetic A-NHP, THP, and SAHP data. As shown in Figure 2d, the A-NHP data can not be well modeled by THP or SAHP, but it can be successfully modeled by—unsurprisingly—A-NHP and—maybe surprisingly—NHP. On the SAHP and THP data,
4The Transformer Hawkes process defines λe(t) def = softplus(w>e [1; t/ti; JeiK(ti)]) where ei@ti is the most recent event before t; the self-attentive Hawkes process conditions the linear projection w on JeK(ti) as well. 5On some datasets, our replicated results are different from their papers. We confirmed that our results are correct via personal communication with the lead authors of Zhang et al. (2020a) and Zuo et al. (2020). 6For users’ convenience, we made a standalone GPU-friendly PyTorch implementation of A-NHP.
A-NHP still gets competitive performance (Figures 2a and 2b). Notably, THP fits the time intervals poorly when it is misspecified, due to its restrictive handling of the passage of time (see section 7).
We then evaluated all these models on following two benchmark real-world datasets.7
MIMIC-II (Lee et al., 2011). This dataset is a collection of de-identified clinical visit records of Intensive Care Unit patients for 7 years.Each patient has a sequence of hospital visit events, and each event records its time stamp and disease diagnosis.
StackOverflow (Leskovec & Krevl, 2014). This dataset represents two years of user awards on a question-answering website: each user received a sequence of badges (of 22 different types).
On MIMIC-II data (Figure 3a), our A-NHP is always a co-winner on each of these tasks; but the other co-winner (NHP or THP) varies across tasks. On StackOverflow data (Figure 3b), our A-NHP is clearly a winner on 2 out of 3 tasks. Compared to NHP, A-NHP also enjoys a computational
7For these datasets, we used the preprocessed versions provided by Mei & Eisner (2017). More details about them can be found in Appendix C.1.2.
advantage, as discussed in sections 1 and 2. Empirically, training an A-NHP only took a fraction of the time that was needed to train an NHP, when sequences are reasonably long. Details can be found in Table 2 of Appendix C.3.

heading: 8.2 A-NDTT VS. NDTT
text: Now we turn to the structured modeling approach presented in section 5. We compare A-NDTT with NDTT on the RoboCup dataset proposed by Mei et al. (2020a). In both cases, we used the NDTT program written by Mei et al. (2020a). The rules are unchanged; the only difference is that our A-NDTT has the new continuous-time Transformer in lieu of the LSTM architecture. We also evaluated the unstructured NHP and A-NHP models on this dataset.
RoboCup (Chen & Mooney, 2008). This dataset logs the actions (e.g., kick, pass) of robot soccer players in the RoboCup Finals 2001–2004. The ball is frequently transferred between players (by passing or stealing), and this dynamically changes the set of possible event types (e.g., only the ball possessor can kick or pass). There are K = 528 event types over all time, but only about 20 of them are possible at any given time. For each prefix of each held-out event sequence, we used minimum Bayes risk to predict the next event’s time, and to predict its participant(s) given its time and action type.
The results are shown in Figure 4. As in section 8.1, we find that A-NHP performs better than NHP on all the evaluation metrics; on log-likelihood and event type prediction, A-NHP is significantly better (paired permutation test, p < 0.05). We now inject domain knowledge into both the LSTM and Transformer approaches, by deriving architectures based on the RoboCup NDTT program (which specifies, for example, that only the ball possessor can kick or pass). The resulting models—NDTT and A-NDTT—are substantial and significant improvements. The difference between A-NDTT and NDTT is not significant: perhaps NDTT already fixes some of the problems with NHP, so it is not sorely in need of the Transformer’s ability to scan an unbounded history for relevant events.8 Appendix C.6 includes more results of A-NDTT vs. NDTT broken down by action types.
Additionally, while A-NDTT does not improve the overall accuracy for this particular NDTT program and dataset, it does achieve overall comparable accuracy with a simpler and shallower architecture (–® in section 1). Like other Transformers, the A-NDTT architecture could be trained on a GPU with parallelism, as outlined in Appendix C.4 (future work).

heading: 9 CONCLUSION
text: We showed how to generalize the Transformer architecture to sequences of discrete events in continuous time. Through our novel continuous-time Transformer, we can incrementally build up rich embeddings of actual and possible events at any time t, from lower-level representations of contextual events. The resulting probability model is highly flexible, and enjoys great parallelism during training. It outperforms other Transformer-based models on multiple synthetic and real-world datasets.
We also showed how to integrate this architecture with NDTT, a neural-symbolic framework that automatically derives neural models from logic programs. Our new version has shown competitive performance, despite having a simpler and shallower architecture.
8While NDTT still uses a fixed-dimensional history—¬ in section 1—the dimensionality is often very high, as the NDTT’s state consists of embeddings of many individual facts. Moreover, each fact’s NDTT embedding is computed by rule-specific LSTMs that see only events that are relevant to that fact, so there is no danger that intervening irrelevant events will displace the relevant ones in the fixed-dimensional LSTM states.

heading: ETHICS STATEMENT
text: Our paper develops a novel probabilistic model for event sequences. Good probabilistic models make it possible to impute missing events, anticipate possible future events, and react accordingly. They can also be used in exploratory data analysis. In addition to advancing the state-of-the-art in this area, our model may require less energy to train than previous models. We used multiple real-world datasets to evaluate our model and those datasets are all de-identified; see section 8 and Appendix C.1.
However, like many other machine learning models, our model may be applied to unethical ends. For example, its abilities of better fitting data and making more accurate predictions could potentially be used for unwanted tracking of individual behavior, e.g. for advertising or surveillance.

heading: REPRODUCIBILITY STATEMENT
text: To facilitate the community to reproduce our results, we are committed to releasing our code when the paper is published. For this submission, we made a thorough documentation of our methodology and experimental details in section 8 and Appendices A–C.

heading: Appendices

heading: A0 PARAMETER DIMENSIONALITY SPECIFICATION FOR A-NDTT
text: In this section we discuss the dimensionality of the fact embeddings JhK(t) in section 5. The type of a fact in the database is given by its functor (forum, member, create, etc.). All facts of the same type have embedding vectors of the same dimensionality, and these dimensionalities are declared by the NDTT program.
This is enough to determine the dimensions of the parameter matrices associated with the deduction rules (Mei et al., 2020a). How about the add rules, however? The form of equation (9) implies that the value vectors v(`)r for add rule r have the same dimensionality as the embedding of the head of r. The key and query vectors for rule r (as used in equation (2)) can share this dimensionality by default, although we are free to override this and specify a different dimensionality for them. The foregoing choices determine the dimensions of the parameter matrices V(`)r ,K (`) r ,Q (`) r associated with rule r.
A final wrinkle is that while the add rule h <- f, g1, ..., gn mainly allows an h fact to attend to preceding f events, it also allows the h fact to attend to itself. Unfortunately, we cannot extract h’s attention key and value using V(`)r and K (`) r , because h may have a different dimensionality from f . A reasonable approach would be to always use zero vectors for this key and value.9

heading: A LIKELIHOOD COMPUTATION DETAILS
text: In this section we discuss the log-likelihood formulas in section 6.
The log-likelihood formula equation 6 has been derived and discussed in previous work (Hawkes, 1971; Liniger, 2009; Mei & Eisner, 2017). Intuitively, during parameter training, each log λei(ti) is increased to explain why ei happened at time ti while ∫ T t=0
λ(t)dt is decreased to explain why no event of any possible type e ∈ {1, . . . , E} ever happened at other times. Note that there is no log under the integral in equation (6). Why? The probability that there was not an event of any type in the infinitesimally wide interval [t, t+ dt) is 1− λ(t)dt, whose log is −λ(t)dt. As discussed in section 6, the integral term in equation (6) is computed using the Monte Carlo approximation detailed by Algorithm 1 of Mei & Eisner (2017), which samples times t.
However, at each sampled time t, that method still requires a summation over all events to obtain λ(t). This summation can be expensive when there are many event types. This is not a serious problem for our standalone A-NHP implementation since it can leverage GPU parallelism. But for the general A-NDTT implementation, it is hard to parallelize the λk(t) computation over k and t. In that case, we use the downsampling trick detailed in Appendix D of Mei et al. (2020a). An alternative would be to replace maximum-likelihood estimation with noise-contrastive estimation, which is quite effective at training NHP and NDTT models (Mei et al., 2020b).

heading: B HOW TO PREDICT EVENTS
text: Section 8 includes a task-based evaluation where we try to predict the time and type of the next event. More precisely, for each event in each held-out sequence, we attempt to predict its time given only the preceding events, as well as its type given both its true time and the preceding events.
We evaluate the time prediction with average L2 loss (yielding a root-mean-squared error, or RMSE) and evaluate the argument prediction with average 0-1 loss (yielding an error rate).
9However, in our present experiments, we did something more complex: we learned special matrices to extract the key and the value from h@t. These matrices were shared by all rules with the same head type, which was only possible because our experimental design in Appendix C.3 used keys of the same dimensionality for all those rules.
Following Mei & Eisner (2017), we use the minimum Bayes risk (MBR) principle to predict the time and type with lowest expected loss. For completeness, we repeat the general recipe in this section.
For the ith event, its time ti has density pi(t) = λ(t) exp(− ∫ t ti−1 λ(t′)dt′). We choose ∫∞ ti−1 tpi(t)dt as the time prediction because it has the lowest expected L2 loss. The integral can be estimated using i.i.d. samples of ti drawn from pi(t) as detailed in Mei & Eisner (2017) and Mei et al. (2019).
Given the next event time ti, we choose the most probable type arg maxe λe(ti) as the type prediction because it minimizes expected 0-1 loss. In some circumstances, one might also like to predict the most probable type out of a restricted set E ′ ( {1, . . . , E}. This allows one to answer questions like “If we know that some event of the form message(eve,T) happened at time ti, then what was the forum T, given all past events?” The answer will simply be arg maxe∈E′ λe(ti).

heading: C EXPERIMENTAL DETAILS

heading: C.1 DATASET DETAILS
text: Table 1 shows statistics about each dataset that we use in this paper.

heading: C.1.1 SYNTHETIC DATA DETAILS
text: In this experiment, we draw data from randomly initialized NHP, A-NHP, SAHP, and THP. For all of them, we take the number of event types to be E = 10. For NHP, the dimensions of event embeddings and hidden states are all 32; for A-NHP, the number of layers (L in our paper) is 2, and the dimensions of time embeddings and event embeddings are 32; for SAHP, the number of layers is 4, and the dimension of hidden states is 32; for THP, the number of layer is 7, and the dimension of hidden states is 32.
For each model, we draw 800, 100, and 100 sequences for training, validation and testing, respectively. For each sequence, the sequence length is drawn from Uniform(49, 99).

heading: C.1.2 OTHER DATA DETAILS
text: For MIMIC-II and StackOverflow, we used the version processed by Du et al. (2016); more details (e.g., about processing) can be found in their paper.
For RoboCup, we used the version processed by Chen & Mooney (2008); please refer to their paper for more details (e.g., data description, processing method, etc)
C.2 IMPLEMENTATION DETAILS
For NHP, our implementation is based on the public Github repositories at https://github.com/ HMEIatJHU/neurawkes (Mei & Eisner (2017), with MIT License) and https://github.com/ HMEIatJHU/neural-hawkes-particle-smoothing (Mei et al. (2019), with BSD 3-Clause “New” or “Revised” License). We made a considerable amount of modifications to their code (e.g., model, thinning algorithm), in order to migrate it to PyTorch 1.7. We built the standalone GPU implementation of A-NHP upon our NHP code.
For NDTT, we used the public Github repository at https://github.com/HMEIatJHU/ neural-datalog-through-time (Mei et al. (2020a), with MIT License). We built A-NDTT upon NDTT.
For THP, we used the public Github repository at https://github.com/SimiaoZuo/ Transformer-Hawkes-Process (Zuo et al. (2020), no license specified).
For SAHP, we used the public Github repository at https://github.com/QiangAIResearcher/ sahp_repo (Zhang et al. (2020a), no license specified).

heading: C.3 TRAINING DETAILS
text: For each model in section 8, we had to specify various dimensionalities. For simplicity, we used a single hyperparameter D and took all vectors to be in RD. This includes the state vectors of NHP, the fact embeddings of NDTT and A-NDTT, and the query, key, and value vectors for the models with attention mechanisms (THP, SAHP, A-NHP, and A-NDTT). For the models with attention mechanisms, we also had to choose the number of layers L.
We tuned these hyperparameters for each combination of model, dataset, and training size (e.g., each bar in Figures 2–4), always choosing the combination of D and L that achieved the best performance on the dev set. Our search spaces were D ∈ {4, 8, 16, 32, 64, 128} and L ∈ {1, 2, 3, 4, 5, 6}. In practice, the optimal D for a model was usually 32 or 64; the optimal L was usually 1, 2, or 3.
To train the parameters for a given model, we used the Adam algorithm (Kingma & Ba, 2015) with its default settings. We performed early stopping based on log-likelihood on the held-out dev set.
In our preliminary experiments, we also tried adding feed-forward layers and layer normalization (Ba et al., 2016) as in the original Transformer architecture (Vaswani et al., 2017), but they didn’t help.
For the experiments in section 8.1, we used the standalone PyTorch implementations for NHP and A-NHP, which are GPU-friendly. We trained each model on an NVIDIA K80 GPU. Table 2 shows their training time per sequence on each dataset.
We run our NDTT and A-NDTT models only on CPUs. This follows Mei et al. (2020a), who did not find an efficient method to leverage GPU parallelism for training NDTT models. The machines we used for NDTT and A-NDTT are 6-core Haswell architectures. On RoboCup, the training time of NDTT and A-NDTT is 62 and 149 seconds per sequence, respectively. We used the same CPU implementation for NHP and A-NHP on RoboCup, rather than the standalone GPU implementation, since the RoboCup sequences are too long to fit in the memory of the K80 GPU. We did this by expressing these models as NDTT programs. The NDTT program for NHP can be found in Appendix F.2 of Mei et al. (2020a); the A-NDTT program for A-NHP can be found in Appendix C.5.1 below. The training time is 66 and 95 seconds per sequence for NHP and A-NHP, respectively.

heading: C.4 TRAINING PARALLELISM
text: We point out that in the future, GPU parallelism could be exploited through the following procedure, given a GPU with enough memory to handle long training sequences. (The layers can be partitioned across multiple GPUs if needed.)
For each training minibatch, the first step is to play each event sequence e1@t1, e2@t2, . . . , eI@tI forward to determine the contents of the database on each interval (0, t1], (t1, t2], . . . , (ti−1, tI ], (tI , T ].
This step runs on CPU, and computes only the boolean facts (“Datalog through time”) without their embeddings (“neural Datalog through time”).
Let F be the set of facts that ever appeared in the database during this minibatch and letR be the set of rules that were ever used to deduce or add them (section 5). Furthermore, let T be the set of times consisting of {t1, . . . , tI} together with the times t that are sampled for the Monte Carlo integral (Appendix A).
A computation graph of sizeO(|R|·I) can now be constructed, as illustrated in Figure 1b, to compute the embeddings JhK(t) of all facts h ∈ F at all times t ∈ T . The layer-` embeddings at time t ∈ T depend on the layer-(`− 1) embeddings at times ti ≤ t, according to the add rules inR. The layer-` embedding of a fact that is deduced at time t also depends on the layer-` embeddings at time t of the facts that it is deduced from, according to the deduction rules inR; this further increases the depth of the computation graph.
For a given fact h ∈ F , JhK(`)(t) can be computed in parallel for all event sequences and all times t ∈ T (even times t when h is not true, although those embeddings will not be used). Multiple facts that are governed by the same NDTT rule r ∈ R can also be handled in parallel, since they use the same r-specific parameters. Thus, a GPU can be effective for this phase. The computation of h (`)
r (t) in equation (9) must take care to limit its attention to just those earlier times when an event occurred that added h via rule r, and the computation of [h](`)(t) in equation (9) must take care to consider only rules r that in fact deduce h at time t because their conditions are true at time t. This masks unwanted parts of the computation, rendering parts of the GPU idle. GPU parallelism will still be worthwhile if a substantial fraction of the computation remains unmasked—which is true for relatively homogenous settings where most facts in F hold true for a large portion of the observed interval [0, T ), even if their embeddings fluctuate.

heading: C.5 A-NDTT PROGRAMS

heading: C.5.1 A-NHP DATALOG PROGRAM
text: In this section, we show how to specify A-NHP (section 3) by an A-NDTT program: 1 is_type(1).
... 2 is_type(N). 3 :- embed(world, 8). 4 :- event(ee, 8). 5 ee(N) :- world, is_type(N) :: prob(N). 6 world <- initinit. 7 world <- ee(N).
where the embedding of world at time t attends to all past events via rule 7, and is used to derive the embeddings and intensities of all of the events e(1), . . . , e(N) at time t, via rule 5. The dashed underline for init indicates that it is an “exogenous” event that is not predicted by our model. The init event always happens at time t = 0. The :: notation was mentioned in footnote 1.
This program is simpler than the NDTT program that specifies the NHP model (see Appendix F.2 of Mei et al. (2020a)). In that program, rule 7 will be replaced by a slightly fancier version, namely world <- e(N), world. That is because world as an additional condition is necessary to resemble the traditional structure of an LSTM: the new LSTM cell of world is a linear combination of its old value and some input, where the linear coefficients (i.e., input and forget gates) and the input depend on both e(N) and the old value of world. Had we just used world <- e(N) instead, the coefficients and the input would only depend on e(N), giving a less rich recurrence. However, this additional richness is not necessary in our A-NHP because our multi-layer attention already captures sufficiently rich contextual information (“attention is all you need”).

heading: C.6 MORE RESULTS
text: The performance of A-NDTT and NDTT is not always comparable for specific action types, as shown in Figure 5 and Figure 6. In terms of data fitting (left figure), A-NDTT is significantly better at the kickoff events while NDTT is better at the others. For time prediction (middle figure), A-NDTT is significantly better at the goal, kickoff, and pass events, but the differences for the other action types are not significant. For action participant prediction (right figure), A-NDTT is significantly better at the kickoff events while there is no difference for the others; both do perfectly well at the goal and kick events such that their dots overlap at the origin.
In Figure 6, we redraw Figure 5 by training A-NDTT with different random seeds. The figures look very similar, thus the per-action differences between NDTT and A-NDTT are fairly consistent.

Review summaries:
The main contribution of this work is a new transformer-based temporal point process (TPP) model. The proposed model defines the conditional intensity at each time $t$ as a function of all past events using the attention mechanism. This is different form existing neural TPP models that typically embed the event history into a vector. Additionally, it is shown how the proposed model can be combined with the Neural Datalog Through Time (NDTT) framework [(Mei et al., 2020)](https://arxiv.org/abs/2006.16723), which allows us to specify certain hard constraints on the event occurrences (such as "events of type x can only occur when certain conditions are met").

A model for sequences of events occurring in the continuous time setting is presented. It uses the self-attention mechanism from the Transformer model, together with some domain-specific masking operations, to create event embeddings that are contextualized by their relation to other (relevant) events that occurred. The model is then extended towards a generative process, which in turn is integrated into a neural datalog through time framework. Experiments show the model to be perform equally or better than baselines based on RNNs or discrete time embeddings.

The paper introduces A-NHP and A-NDTT that tackle the problem of continuous time sequences and neural-symbolic computing with a time component using transformers and attention. The paper explains their model and techniques mainly with equations. The work seems primarily motivated by previous work on Hawkes processes and neural datalog through time NDTT. They improve by adding a probability model that allows them to embed all possible events and using transformers instead of LSTMs for parallelization. They achieve strong experimental results, especially in StackOverflow and RoboCup.