# C5\_W4\_A1 Exercise 4 Encoder Layer

**URL:** <https://community.deeplearning.ai/t/c5-w4-a1-exercise-4-encoder-layer/24147>\
**Category:** Sequence Models\
**Tags:** coursera-platform\
**Created:** [July 29, 2021, 8:00pm UTC](https://community.deeplearning.ai/t/c5-w4-a1-exercise-4-encoder-layer/24147 "2021-07-29T20:00:33Z")\
**Posts on this page:** 16\
**Page:** 1

<div class="post-metadata">

**Author:** ![rameshgopalan](https://avatars.discourse-cdn.com/v4/letter/r/838e76/32.png) [@rameshgopalan](https://community.deeplearning.ai/u/rameshgopalan)\
**Post date:** [July 29, 2021, 8:00pm UTC](https://community.deeplearning.ai/t/c5-w4-a1-exercise-4-encoder-layer/24147/1 "2021-07-29T20:00:33Z")

</div>

## need help to understand right syntax (?) for Encoder Layer - am i not slicing input sequence X correctly ? The following code does NOT work - please remove redact as appropriate.

```auto
# START CODE HERE
# moderator edit: code removed     
# END CODE HERE

```

```
    return encoder_layer_out

```

---

<div class="post-metadata">

**Author:** ![TMosh](https://sea1.discourse-cdn.com/dlai/user_avatar/community.deeplearning.ai/tmosh/32/9321_2.png) [@TMosh](https://community.deeplearning.ai/u/TMosh)\
**Post date:** [July 29, 2021, 8:24pm UTC](https://community.deeplearning.ai/t/c5-w4-a1-exercise-4-encoder-layer/24147/2 "2021-07-29T20:24:00Z")

</div>

You should use the functions created in the constructor.  
So instead of calling MulltiHeadAttention() directly, you use “self.mha(…)” from the constructor.

---

<div class="post-metadata">

**Author:** ![rameshgopalan](https://avatars.discourse-cdn.com/v4/letter/r/838e76/32.png) [@rameshgopalan](https://community.deeplearning.ai/u/rameshgopalan)\
**Post date:** [July 29, 2021, 10:55pm UTC](https://community.deeplearning.ai/t/c5-w4-a1-exercise-4-encoder-layer/24147/3 "2021-07-29T22:55:12Z")

</div>

Thanks TMosh, however I am very confused about the arguments to pass to self.mha( or indeed the subsequent functions (out, ffn\_output,…) in this Exercise 4.

The comments suggest : (batch\_size,input\_seq\_len,fully\_connected\_dim) but the ‘Additional hints’ section suggests (to me) something more complicated.

Again, any tips appreciated.

**NON-WORKING CODE BELOW** \*\*\*

```auto

# START CODE HERE

# moderator edit: code removed

# END CODE HERE

return encoder_layer_out

```

---

<div class="post-metadata">

**Author:** ![TMosh](https://sea1.discourse-cdn.com/dlai/user_avatar/community.deeplearning.ai/tmosh/32/9321_2.png) [@TMosh](https://community.deeplearning.ai/u/TMosh)\
**Post date:** [July 30, 2021, 1:18am UTC](https://community.deeplearning.ai/t/c5-w4-a1-exercise-4-encoder-layer/24147/4 "2021-07-30T01:18:36Z")

</div>

For self-attention, the ‘x’ matrix is used for each of Q, V, and K. See this from the instructions:

 ![image](https://global.discourse-cdn.com/dlai/original/2X/3/3e06d2276fb0aac56a190ba276e3a9fd7c81358e.png)

The instructions provide similar guidance for all the other lines of code.

---

<div class="post-metadata">

**Author:** ![TMosh](https://sea1.discourse-cdn.com/dlai/user_avatar/community.deeplearning.ai/tmosh/32/9321_2.png) [@TMosh](https://community.deeplearning.ai/u/TMosh)\
**Post date:** [July 30, 2021, 1:22am UTC](https://community.deeplearning.ai/t/c5-w4-a1-exercise-4-encoder-layer/24147/5 "2021-07-30T01:22:42Z")

</div>

If you’re going to keep posting your code, please use the “preformatted text” tag. This will prevent the code comments from being interpreted as Markup text (that’s why your post is full of **bold text** ).

---

<div class="post-metadata">

**Author:** ![rameshgopalan](https://avatars.discourse-cdn.com/v4/letter/r/838e76/32.png) [@rameshgopalan](https://community.deeplearning.ai/u/rameshgopalan)\
**Post date:** [July 30, 2021, 6:21pm UTC](https://community.deeplearning.ai/t/c5-w4-a1-exercise-4-encoder-layer/24147/6 "2021-07-30T18:21:20Z")

</div>

Hello TMosh, i am following the instructions as best i can, to apply the boolean mask, and leave training Default, not applied till Dropout ? but the error now is that call () missing a positional argument ‘value’  
_**dysfunctional code below -preformatted text this time:)**_\*\*\*\*\*\*

```auto
 # START CODE HERE
 # moderator edit: code removed
 # END CODE HERE
        

```

---

<div class="post-metadata">

**Author:** ![TMosh](https://sea1.discourse-cdn.com/dlai/user_avatar/community.deeplearning.ai/tmosh/32/9321_2.png) [@TMosh](https://community.deeplearning.ai/u/TMosh)\
**Post date:** [July 30, 2021, 6:49pm UTC](https://community.deeplearning.ai/t/c5-w4-a1-exercise-4-encoder-layer/24147/7 "2021-07-30T18:49:39Z")

</div>

Please post a screen capture image showing the entire error message and the whole assert stack.

---

<div class="post-metadata">

**Author:** ![TMosh](https://sea1.discourse-cdn.com/dlai/user_avatar/community.deeplearning.ai/tmosh/32/9321_2.png) [@TMosh](https://community.deeplearning.ai/u/TMosh)\
**Post date:** [July 30, 2021, 6:54pm UTC](https://community.deeplearning.ai/t/c5-w4-a1-exercise-4-encoder-layer/24147/8 "2021-07-30T18:54:44Z")

</div>

> [@rameshgopalan](#):
>
> `attn_output = self.mha(x,attention_mask=mask)`

Read my previous reply again. You need to pass ‘x’ to the self.mha(…) function three times - once for each of the Q, V, and K matrices.

---

<div class="post-metadata">

**Author:** ![rameshgopalan](https://avatars.discourse-cdn.com/v4/letter/r/838e76/32.png) [@rameshgopalan](https://community.deeplearning.ai/u/rameshgopalan)\
**Post date:** [July 30, 2021, 7:28pm UTC](https://community.deeplearning.ai/t/c5-w4-a1-exercise-4-encoder-layer/24147/9 "2021-07-30T19:28:10Z")

</div>

Thanks, but I may still be missing a syntax or format issue:

{moderator edit: code removed}

the screenshot of (bottom bit only) of error message:

 ![image001.png](https://global.discourse-cdn.com/dlai/original/2X/8/88ce7e0f77bf90596ad2f5058ded66ce416c850d.png)

---

<div class="post-metadata">

**Author:** ![TMosh](https://sea1.discourse-cdn.com/dlai/user_avatar/community.deeplearning.ai/tmosh/32/9321_2.png) [@TMosh](https://community.deeplearning.ai/u/TMosh)\
**Post date:** [July 30, 2021, 7:49pm UTC](https://community.deeplearning.ai/t/c5-w4-a1-exercise-4-encoder-layer/24147/10 "2021-07-30T19:49:15Z")

</div>

That part of the assert log doesn’t help me, because I can’t see which line of your code caused the issue.

---

<div class="post-metadata">

**Author:** ![TMosh](https://sea1.discourse-cdn.com/dlai/user_avatar/community.deeplearning.ai/tmosh/32/9321_2.png) [@TMosh](https://community.deeplearning.ai/u/TMosh)\
**Post date:** [July 30, 2021, 7:49pm UTC](https://community.deeplearning.ai/t/c5-w4-a1-exercise-4-encoder-layer/24147/11 "2021-07-30T19:49:54Z")

</div>

You only need self.mah(x, x, x, mask).

If you’re having a problem, it might be somewhere else.

---

<div class="post-metadata">

**Author:** ![rameshgopalan](https://avatars.discourse-cdn.com/v4/letter/r/838e76/32.png) [@rameshgopalan](https://community.deeplearning.ai/u/rameshgopalan)\
**Post date:** [July 30, 2021, 9:28pm UTC](https://community.deeplearning.ai/t/c5-w4-a1-exercise-4-encoder-layer/24147/12 "2021-07-30T21:28:15Z")

</div>

sorry to bother, but i used exactly what you have had

```auto
# START CODE HERE
# moderator edit: code removed
# END CODE HERE

```

* * *

TypeError Traceback (most recent call last)  
 in   
1 # UNIT TEST  
----\> 2 EncoderLayer\_test(EncoderLayer)

~/work/W4A1/public\_tests.py in EncoderLayer\_test(target)  
84 encoder\_layer1 = target(4, 2, 8)  
85 tf.random.set\_seed(10)  
—\> 86 encoded = encoder\_layer1(q, True, np.array([[1, 0, 1]]))  
87  
88 assert tf.is\_tensor(encoded), “Wrong type. Output must be a tensor”

/opt/conda/lib/python3.7/site-packages/tensorflow/python/keras/engine/base\_layer.py in **call** (self, \*args, \*\*kwargs)  
1010 with autocast\_variable.enable\_auto\_cast\_variables(  
1011 self.\_compute\_dtype\_object):  
 → 1012 outputs = call\_fn(inputs, \*args, \*\*kwargs)  
1013  
1014 if self.\_activity\_regularizer:

in call(self, x, training, mask)  
39 # START CODE HERE  
40 # calculate self-attention using mha(~1 line). Dropout will be applied during training  
—\> 41 attn\_output = self.mha(x,x,x,mask) # Self attention (batch\_size, input\_seq\_len, fully\_connected\_dim)  
42  
43 # apply layer normalization on sum of the input and the attention output to get the

/opt/conda/lib/python3.7/site-packages/tensorflow/python/keras/engine/base\_layer.py in **call** (self, \*args, \*\*kwargs)  
1010 with autocast\_variable.enable\_auto\_cast\_variables(  
1011 self.\_compute\_dtype\_object):  
 → 1012 outputs = call\_fn(inputs, \*args, \*\*kwargs)  
1013  
1014 if self.\_activity\_regularizer:

/opt/conda/lib/python3.7/site-packages/tensorflow/python/keras/layers/multi\_head\_attention.py in call(self, query, value, key, attention\_mask, return\_attention\_scores, training)  
463 # H = `size_per_head`  
464 # `query` = [B, T, N ,H]  
 → 465 query = self.\_query\_dense(query)  
466  
467 # `key` = [B, S, N, H]

/opt/conda/lib/python3.7/site-packages/tensorflow/python/keras/engine/base\_layer.py in **call** (self, \*args, \*\*kwargs)  
1006 with ops.name\_scope\_v2(name\_scope):  
1007 if not self.built:  
 → 1008 self.\_maybe\_build(inputs)  
1009  
1010 with autocast\_variable.enable\_auto\_cast\_variables(

/opt/conda/lib/python3.7/site-packages/tensorflow/python/keras/engine/base\_layer.py in \_maybe\_build(self, inputs)  
2708 # operations.  
2709 with tf\_utils.maybe\_init\_scope(self):  
 → 2710 self.build(input\_shapes) # pylint:disable=not-callable  
2711 # We must set also ensure that the layer is marked as built, and the build  
2712 # shape is stored since user defined build functions may not be calling

/opt/conda/lib/python3.7/site-packages/tensorflow/python/keras/layers/einsum\_dense.py in build(self, input\_shape)  
152 constraint=self.kernel\_constraint,  
153 dtype=self.dtype,  
 → 154 trainable=True)  
155  
156 if bias\_shape is not None:

/opt/conda/lib/python3.7/site-packages/tensorflow/python/keras/engine/base\_layer.py in add\_weight(self, name, shape, dtype, initializer, regularizer, trainable, constraint, use\_resource, synchronization, aggregation, \*\*kwargs)  
637 synchronization=synchronization,  
638 aggregation=aggregation,  
 → 639 caching\_device=caching\_device)  
640 if regularizer is not None:  
641 # TODO(fchollet): in the future, this should be handled at the

/opt/conda/lib/python3.7/site-packages/tensorflow/python/training/tracking/base.py in \_add\_variable\_with\_custom\_getter(self, name, shape, dtype, initializer, getter, overwrite, \*\*kwargs\_for\_getter)  
808 dtype=dtype,  
809 initializer=initializer,  
 → 810 \*\*kwargs\_for\_getter)  
811  
812 # If we set an initializer and the variable processed it, tracking will not

/opt/conda/lib/python3.7/site-packages/tensorflow/python/keras/engine/base\_layer\_utils.py in make\_variable(name, shape, dtype, initializer, trainable, caching\_device, validate\_shape, constraint, use\_resource, collections, synchronization, aggregation, partitioner)  
127 # TODO(apassos,rohanj) figure out how to remove collections from here so we  
128 # can remove the V1.  
 → 129 variable\_shape = tensor\_shape.TensorShape(shape)  
130 return tf\_variables.VariableV1(  
131 initial\_value=init\_val,

/opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/tensor\_shape.py in **init** (self, dims)  
756 “”"  
757 if isinstance(dims, (tuple, list)): # Most common case.  
 → 758 self.\_dims = [Dimension(d) for d in dims]  
759 elif dims is None:  
760 self.\_dims = None

/opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/tensor\_shape.py in (.0)  
756 “”"  
757 if isinstance(dims, (tuple, list)): # Most common case.  
 → 758 self.\_dims = [Dimension(d) for d in dims]  
759 elif dims is None:  
760 self.\_dims = None

/opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/tensor\_shape.py in **init** (self, value)  
204 TypeError("Dimension value must be integer or None or have "  
205 “an **index** method, got value ‘{0!r}’ with type ‘{1!r}’”  
 → 206 .format(value, type(value))), None)  
207 if self.\_value \< 0:  
208 raise ValueError("Dimension d must be \>= 0" self.\_value)

/opt/conda/lib/python3.7/site-packages/six.py in raise\_from(value, from\_value)

TypeError: Dimension value must be integer or None or have an **index** method, got value ‘\< **main**.EncoderLayer object at 0x7ff5a00c72d0\>’ with type ‘\<class ‘ **main**.EncoderLayer’\>’

```auto

```

---

<div class="post-metadata">

**Author:** ![rameshgopalan](https://avatars.discourse-cdn.com/v4/letter/r/838e76/32.png) [@rameshgopalan](https://community.deeplearning.ai/u/rameshgopalan)\
**Post date:** [August 1, 2021, 6:06pm UTC](https://community.deeplearning.ai/t/c5-w4-a1-exercise-4-encoder-layer/24147/13 "2021-08-01T18:06:58Z")

</div>

requesting any tip or hint as to the problem here - I have tried TMosh recommended  
using self.mha(x,x,x,mask) to pass x to Q, V, K as self-attention, and the Boolean mask

- so much of these problems sets is about the implementation, not the concepts themselves ☹

---

<div class="post-metadata">

**Author:** ![rameshgopalan](https://avatars.discourse-cdn.com/v4/letter/r/838e76/32.png) [@rameshgopalan](https://community.deeplearning.ai/u/rameshgopalan)\
**Post date:** [August 1, 2021, 6:09pm UTC](https://community.deeplearning.ai/t/c5-w4-a1-exercise-4-encoder-layer/24147/14 "2021-08-01T18:09:36Z")

</div>

TMosh or other Mentor, please help, I am twisting my head not on some conceptual issue but possibly syntax or tf.keras implementation question (sorry, but am a total novice there;-(

The last recommended hint did not work…

```auto

# START CODE HERE

# moderator edit: code removed

# END CODE HERE

```

---

<div class="post-metadata">

**Author:** ![TMosh](https://sea1.discourse-cdn.com/dlai/user_avatar/community.deeplearning.ai/tmosh/32/9321_2.png) [@TMosh](https://community.deeplearning.ai/u/TMosh)\
**Post date:** [August 3, 2021, 4:14am UTC](https://community.deeplearning.ai/t/c5-w4-a1-exercise-4-encoder-layer/24147/15 "2021-08-03T04:14:19Z")

</div>

I have found the error in your code.  
` ffn_output = self.dropout_ffn(ffn_output,training=True)`  
That line should use “training=training”.

When you force training=True, you will get incorrect results when the unit test turns the training to False.

---

<div class="post-metadata">

**Author:** ![TMosh](https://sea1.discourse-cdn.com/dlai/user_avatar/community.deeplearning.ai/tmosh/32/9321_2.png) [@TMosh](https://community.deeplearning.ai/u/TMosh)\
**Post date:** [July 12, 2023, 3:25pm UTC](https://community.deeplearning.ai/t/c5-w4-a1-exercise-4-encoder-layer/24147/16 "2023-07-12T15:25:09Z")

</div>

Closed on July 12, 2023, 3:25pm UTC


